Swift 准备 segue - 将数据从一个 View Controller 发送到另一个

标签 swift collectionview

我想从一个 View Controller 移动到另一个 View Controller 并发送 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

    }

通过单击我得到:“ fatal error :在展开可选值时意外发现 nil” 我做错了什么?

最佳答案

如果你在 StoryBoard 中给出了 segue 不要在 didSelectItem 中调用这个 self.performSegueWithIdentifier("chosenPerson", sender: self) 方法

如果你在 Storyboard中给出了 segue override func prepareForSegue - 这个方法在 didSelectItem 调用之后先调用

请引用 Storyboard一次(下图示例)

我认为问题出在 self.usersArray[indexPath.row].userId 可能会返回 nil

swift 2:

self.performSegueWithIdentifier("chosenPerson", sender: self)

swift 3:

self.performSegue(withIdentifier: "chosenPerson", sender: self)

swift 2:

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

}

swift 3:

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

        }




    }
}

enter image description here

关于Swift 准备 segue - 将数据从一个 View Controller 发送到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39830552/

相关文章:

ios - 无法让 Swift 使用我的通用 == 运算符

ios - 如何使用自定义 UITableViewCell 制作 Hozirontal UITableView

ios - DidSelect 突出显示更改 View 颜色不起作用

ios - 防止 UICollectionView 在 vi​​ew.layoutIfNeeded 期间设置动画

iOS swift后台线程阻塞主线程

ios - 使用自动布局根据条件调整标签位置。

swift - 在 swift 3 中播放音频时如何进入当前 viewController?

swift - UICollectionView - 为什么不调用这些方法?

ios - 如何快速裁剪collectionview单元格之外的部分图像

ios - 照片框架