【发布时间】:2017-02-14 16:51:42
【问题描述】:
我正在学习 swift 2。我正在尝试将被点击的单元格 (UITableView) 的数据传递给新的视图控制器。但我经常收到错误:代码行“destination!.label.text = valueToPass”的“unexpectedly found nil while unwrapping an Optional value”。
以下是我的代码。
我可以知道我应该怎么做才能解决它吗?我已经花了几个小时,但仍然坚持下去。
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow;
let Mycell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
valueToPass = (Mycell.textLabel?.text)!
performSegueWithIdentifier("webNext", sender: self)
print("\(indexPath!.row)")
print(valueToPass)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "webNext") {
let destination = segue.destinationViewController as? web___ViewController
destination!.label.text = valueToPass
}
}
【问题讨论】:
-
destination!导致了该问题。你没有destinationViewController。试试if let destination = segue.destinationViewController as? web___ViewController { }。在该块内,destination不会是nil -
对学习的两个建议: 1) 习惯命名约定——变量和方法/函数以小写字母开头,类、结构和枚举以大写字母开头并且没有下划线。 2)从不从表格视图单元格(视图)获取数据,从数据源数组(模型)获取数据
标签: ios swift uitableview pass-data unwrap