为什么我不能在swift中的prepareForSegue方法中强制发送发件人?

时间:2016-03-21 21:03:52

标签: ios swift segue uistoryboardsegue

我的应用程序中有一个列表视图,我在那里动态添加单元格。 对于我希望附加segue的每个单元格,并且由于它在用户按下单元格时打开UIViewController(称为FullUser)(UIViewController将包含此segue传递的数据,从用户选择的特定单元格中获取,存储在名为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对象,那么我怎么能把它传递到那里呢?

2 个答案:

答案 0 :(得分:0)

将逻辑移入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!
    }
}

答案 1 :(得分:0)

我建议您在user课程中添加FullUser属性,并在设置用户时更新您的用户界面,所以它看起来像这样:

class FullUser: UIViewController {
    var user: SingleUser? {
        didSet {
            configureView()
        }
    }

    @IBOutlet weak var usernameField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        configureView() // Call configure in viewDidLoad because
        // your user might be set before the view is loaded
    }

    func configureView() {
        guard let user = user where isViewLoaded() else { return }
        usernameField.text = user.username
    }
}

然后您的prepareForSegue实施可以变得更加简单。我还建议在if中展开选项而不是使用强制解包(你应该尽可能多地强行展开!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let fullUserDetails = segue.destinationViewController as? FullUser,
    user = sender as? SingleUser {
        fullRequestDetails.user = user
    }
}