Error: Found nil while unwrapping an Optional value; While Pass Data to the New Controller [duplicate]

拈花ヽ惹草 提交于 2019-12-11 04:11:12

问题


I'm learning swift 2. I'm trying to pass the data of the cell (UITableView) that is tapped to the new View Controller. But I constantly get the error of: "unexpectedly found nil while unwrapping an Optional value" for the code line "destination!.label.text = valueToPass".
Below is my code.
May I know what should I do to solve it? I have spent hours but still stuck with it.

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
    }

}

回答1:


By doing this: destination!.label.text = valueToPass, you are already setting some text to the label before even it is drawn or presented.

Rather use some variable to pass data to next view and show that data inside viewDidLoad.

let destination = segue.destinationViewController as? web___ViewController

destination!.strValue = valueToPass

Web_VC:

var strValue:String?

func viewDidLoad(){
   super.viewDidLoad()

   label.text = strValue!
}


来源:https://stackoverflow.com/questions/39887587/error-found-nil-while-unwrapping-an-optional-value-while-pass-data-to-the-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!