【问题标题】:Error: Found nil while unwrapping an Optional value; While Pass Data to the New Controller [duplicate]错误:在展开可选值时发现 nil;将数据传递给新控制器时[重复]
【发布时间】: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! 导致了该问题。你没有destination ViewController。试试if let destination = segue.destinationViewController as? web___ViewController { }。在该块内,destination 不会是 nil
  • 学习的两个建议: 1) 习惯命名约定——变量和方法/函数以小写字母开头,类、结构和枚举以大写字母开头并且没有下划线。 2)从不从表格视图单元格(视图)获取数据,从数据源数组(模型)获取数据

标签: ios swift uitableview pass-data unwrap


【解决方案1】:

通过这样做:destination!.label.text = valueToPass,您已经在绘制或呈现标签之前为标签设置了一些文本。

而是使用一些变量将数据传递到下一个视图并在viewDidLoad 中显示该数据。

let destination = segue.destinationViewController as? web___ViewController

destination!.strValue = valueToPass

Web_VC:

var strValue:String?

func viewDidLoad(){
   super.viewDidLoad()

   label.text = strValue!
}

【讨论】:

  • 谢谢你教我原因和详细代码。它有效!
猜你喜欢
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 2014-08-29
  • 2014-12-27
  • 1970-01-01
相关资源
最近更新 更多