我正在使用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。
任何帮助将不胜感激。
这是一个有两个假设的一般解决方案。首先,UserId不是UILabel。其次,您打算使用view在第二行中实例化的代码,而不是使用secondViewController
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] }
这是仪表板的外观:
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 } ... }