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

时间:2014-10-31 14:10:44

标签: ios swift

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

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.
}

但我收到此错误:   致命错误:在展开Optional值时意外发现nil。

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:5)

这是一个有两个假设的通用解决方案。首先,UserId不是UILabel。其次,您打算使用在第二行中实例化的view,而不是使用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的样子:

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
    }

    ...
}

答案 1 :(得分:3)

我们可以使用" struct"传递价值。在swift 3

  1. 在项目中创建一个swift文件
  2. 在如下创建的swift文件中创建一个类

        class StructOperation {
          struct glovalVariable {
          static var userName = String();
         }
     }
    
  3. 将值赋予"静态var userName" "的变量struct glovalVariable" in" StructOperation"来自First View Controller的类

     @IBAction func btnSend(_ sender: Any) {
        StructOperation.glovalVariable.userName = "Enamul Haque";
       //Code Move to Sencon View Controller
     }
    
  4. 在目标视图控制器中获取类似下面的值

     var username = StructOperation.glovalVariable.userName;
    

答案 2 :(得分:0)

在secondViewController中是UserId(strong, nonatomic)吗?

如果它很弱,它会立即发送垃圾。你必须强大。