Swift为Segue做准备-将数据从一个视图控制器发送到另一个 [英] Swift prepare for segue - Send data from one view controller to another

查看:101
本文介绍了Swift为Segue做准备-将数据从一个视图控制器发送到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个视图控制器移动到另一个,并发送userId:

I want to move from one view controller to another and send 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

    }

通过单击我得到:致命错误:在展开可选值时意外发现nil
我做错了什么?

by clicking I get: "fatal error: unexpectedly found nil while unwrapping an Optional value" what I do wrong?

推荐答案

如果您在StoryBoard中提供了segue,请不要将其称为 self.performSegueWithIdentifier( chosenPerson,发件人:self) didSelectItem中的方法

If you have given segue in StoryBoard DON'T Call this self.performSegueWithIdentifier("chosenPerson", sender: self) method in didSelectItem

如果您在情节提要中给出了segue 覆盖功能func prepareForSegue -此方法在didSelectItem之后首先调用呼叫

If you have given segue in storyboard override func prepareForSegue - this method calls first after that didSelectItem calls

请一次引用storyBoard(在示例图片下)

Please refer storyBoard once (below Image for Sample)

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

I think problem is in self.usersArray[indexPath.row].userId May this returns 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

        }




    }
}

这篇关于Swift为Segue做准备-将数据从一个视图控制器发送到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆