我的应用程序中有一个列表视图,并且在其中动态添加单元格。
对于每个我想要附加单元格的单元格,并感谢它在用户按下单元格时打开一个UIViewController(称为FullUser)(UIViewController将包含由该单元格传递的数据,该数据是从用户选择的特定单元格中获取的,存储在一种名为SingleUser的结构)。
所以我有这种方法:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath) as! SingleEventCell

    let user =  self.items[indexPath.row] as? SingleUser

    self.performSegueWithIdentifier("fullUserFromListSegue", sender: user)
    }


接着:

var fullUserDetails: FullUser?

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     if (segue.identifier == "fullUserFromListSegue"){

        fullUserDetails = segue.destinationViewController as? FullUser

       //now I want to set the textfield on the other panel:

        let user2 =  sender as? SingleUser

        var username = user2?.username

        fullRequestDetails!.username.text = username!
    }
}


但是我遇到了错误,当我在调试器中检查它时,我看到user2为零。为什么这样?我想在其中存储一个SingleUser对象,如何将其传递到那里?

最佳答案

将逻辑移到prepareForSegue()函数中,然后在目标视图控制器上设置属性。请注意,如果destinationViewController不是您期望的类,则应在情节提要中检入视图控制器设置。

var fullUserDetails: FullUser?

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // check the destintation view controller is of correct class
    if let fullUserDetails = segue.destinationViewController as? FullUser {
        let path = self.tableView.indexPathForSelectedRow
        let user =  self.items[path.row] as? SingleUser

        var username = user?.username

        fullRequestDetails!.username.text = username!
    }
}

10-05 22:55