将值传递给模态 UIViewController - Swift

passing values to a Modal UIViewController - Swift

我在 UICollectionView 中有一个用户配置文件列表,当我点击其中一个用户时,我有一个 segue,它以模态方式显示用户配置文件,但是我似乎无法将值从一个视图传递到另一个视图.例如..图像数据,用户名等

在我的 UICollectionViewController 上,我有以下内容:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "showSelectedUserProfile" {

        let cell = sender as! GrafterCell
        let SP = segue.destinationViewController as! SelectedProfileViewController
        let indexPath = self.collectionView?.indexPathForCell(cell)

        var username = allUsernames[indexPath!.row]
        SP.username.text = username

    }
}

cell 是来自集合视图的单元格,SP 如果是目标视图控制器

当我 运行 脚本时,出现以下错误

fatal error: unexpectedly found nil while unwrapping an Optional value

它显​​示 SP.username 是 nil 我不知道为什么它是 nil 因为它连接到 Class 并调用 username

class SelectedProfileViewController: UIViewController {

@IBOutlet weak var btnHideSelectedProfileViewController: UIButton!
@IBOutlet weak var userProfilePicture: UIImageView!
@IBOutlet weak var username: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    self.navigationController?.navigationBarHidden = true
}

@IBAction func btnHideSelectedProfileViewControllerClicked(sender: AnyObject) {

    self.dismissViewControllerAnimated(true, completion: nil)

}

}

您有一个包含 属性 username 和 属性 text 的对象数组。据我所知,您可能正在存储一个对象数组,其中 username 属性 是 UILabel?

这将是非常糟糕的设计。您的数据数组应该只有数据对象,而不是 UI 元素。切勿使用 UI 元素的内容来存储和检索数据(这似乎是您正在做的)。 UI 元素应仅用于显示数据。

您需要为目标控制器提供一个 String 类型的 属性 来保存用户名信息。

此外,请勿调用具有误导性的标签 username。如果它是一个标签,将其命名为 nameLabel 以使代码对外部 reader.

可读和理解