在Swift中将值从一个视图控制器传递到另一个视图控制器

在Swift中将值从一个视图控制器传递到另一个视图控制器

本文介绍了在Swift中将值从一个视图控制器传递到另一个视图控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Swift,我在tableview的didSelectRowAtIndexPath方法中遇到了错误。
我想将值传递给另一个视图控制器,即'secondViewController'。这里EmployeesId是一个数组。相关代码如下:

I am working on Swift, I've got an error in tableview's didSelectRowAtIndexPath method.I want to pass a value to another view controller i.e 'secondViewController'. Here EmployeesId is an Array. The relevant code is as follows:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard

    self.navigationController?.pushViewController(view, animated: true)
    secondViewController.UserId = employeesId[indexPath.item]  //getting an error here.
}

但我收到此错误:
致命错误:意外发现在解包可选值时为零。

But I am getting this Error: fatal error: unexpectedly found nil while unwrapping an Optional value.

任何帮助都将受到赞赏。

Any help will be appreciated.

推荐答案

这是一个有两个假设的一般解决方案。首先,UserId不是UILabel。其次,你打算使用在第二行实例化的 view ,而不是使用 secondViewController

Here's a general solution with two assumptions. First, UserId is not a UILabel. Second, you meant to use view which was instantiated in the second line, instead of using secondViewController

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var view: Dashboard = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as Dashboard

    self.navigationController?.pushViewController(view, animated: true)
    view.UserId = employeesId[indexPath.row]
}

这是Dashboard的样子:

Here's what Dashboard looks like:

class Dashboard: UIViewController {
    var UserId: String!
    @IBOutlet var userIDLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        userIDLabel.text = UserId
    }

    ...
}

这篇关于在Swift中将值从一个视图控制器传递到另一个视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:59