我在 UICollectionView 中有一个用户配置文件列表,当我点击其中一个用户时,我有一个 segue,它以模态方式显示用户配置文件,但是我似乎无法将值从一个 View 传递到另一个 View 。例如..图像数据,用户名等。
在我的 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
是来自 Collection View 的单元格,如果是目标 View Controller 则为 SP
当我运行脚本时出现以下错误
fatal error :在展开可选值时意外发现 nil
它显示 SP.username
是 nil 我不知道为什么它是 nil 因为它连接到类并调用 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 元素应该仅用于显示数据。
您需要为目标 Controller 提供一个 String
类型的属性来保存用户名信息。
此外,不要调用具有误导性的标签 username
。如果它是一个标签,将其命名为 nameLabel
以使代码对于外部读者来说是可读和可理解的。
关于ios - 将值传递给模态 UIViewController - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29736550/