我想从一个视图控制器移动到另一个视图控制器并发送userId:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("chosenPerson", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "chosenPerson" {
let chosenPerson = segue.destinationViewController as? chosenPersonViewController
let indexPaths = self.collectionView!.indexPathsForSelectedItems()!
let indexPath = indexPaths[0] as NSIndexPath
chosenPerson!.userID = self.usersArray[indexPath.row].userId
}
点击我得到:“致命错误:在打开一个Optional值时意外发现nil” 我做错了什么?
答案 0 :(得分:3)
如果你在StoryBoard中给了segue,请在didSelectItem中调用 self.performSegueWithIdentifier(" selectedPerson",sender:self)方法
如果你在storyboard中给出了segue override func prepareForSegue - 这个方法在didSelectItem调用后首先调用
请参考storyBoard一次(图片样本下方)
我认为问题出在 self.usersArray [indexPath.row] .userId 这可能会返回nil
Swift2:
self.performSegueWithIdentifier("chosenPerson", sender: self)
Swift3:
self.performSegue(withIdentifier: "chosenPerson", sender: self)
Swift2:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "chosenPerson" {
let chosenPerson = segue.destinationViewController as? chosenPersonViewController
let indexPaths = self.collectionView!.indexPathsForSelectedItems()!
let indexPath = indexPaths[0] as NSIndexPath
chosenPerson!.userID = self.usersArray[indexPath.row].userId //May it found nil please re - check array values
}
Swift3:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "chosenPerson" {
let chosenPerson = segue.destination as! chosenPersonViewController
if let indexPath = collectionView.indexPathForSelectedItem {
chosenPerson!.userID = self.usersArray[indexPath.row].userId //May it found nil please re - check array values
}
}
}
答案 1 :(得分:1)
执行segue时,将indexPath作为发送方传递并尝试使用此switch语句。如果您在选择单元格时看到"unknown segue"
打印出来,则目标控制器的类型不是chosenPersonViewController
。
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("chosenPerson", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch (segue.destinationViewController, sender) {
case (let controller as chosenPersonViewController, let indexPath as NSIndexPath):
controller.userID = usersArray[indexPath.row].userId
default:
print("unknown segue")
break
}
}
答案 2 :(得分:0)
一个可能的问题可能是你的故事板中没有为你的segue设置标识符" selectedPerson"。要解决此问题,首先要确保在第一个和第二个视图控制器之间有一个segue,可以通过控件将一个视图从一个视图控制器拖到另一个视图控制器来创建。
然后确保segue具有标识符,具体为:" selectedPerson"。要执行此操作:单击前两个视图控制器之间的segue,然后导航到属性选项卡,然后将标识符框设置为" selectedPerson"。使用您的更改保存故事板,现在您应该能够使用该标识符调用prepareForSegue,而不会遇到致命错误。