我目前在destViewController.titleLabel.text =“Testing Segue”中打开一个致命错误时意外发现nil,同时解包一个可选值。
如何修复它,因为它在转到SecondViewController时遇到错误?我如何避免在titleLabel.text上获得nil?
class ViewController: UIViewController {
@IBAction func action(sender: AnyObject) {
let alertController: UIAlertController = UIAlertController (title: "Next Page", message: "", preferredStyle: .Alert)
let yesAction = UIAlertAction (title: "YES", style: .Default ) { action -> Void in self.performSegueWithIdentifier("test", sender: self)
}
alertController.addAction (yesAction)
self.presentViewController(alertController, animated: true, completion: nil)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "test") {
let destViewController : SecondViewController = segue.destinationViewController as SecondViewController
destViewController.titleLabel.text = "Testing Segue"
}
}
}
答案 0 :(得分:2)
首先,在您的ViewController
中更新您的代码:
class ViewController: UIViewController {
@IBAction func action(sender: AnyObject) {
let alertController: UIAlertController = UIAlertController (title: "Next Page", message: "", preferredStyle: .Alert)
let yesAction = UIAlertAction (title: "YES", style: .Default ) { action -> Void in self.performSegueWithIdentifier("test", sender: self)
}
alertController.addAction (yesAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "test") {
let destViewController : SecondViewController = segue.destinationViewController as SecondViewController
destViewController.textlbl = "Testing Segue"
}
}
}
之后我认为你无法用你的方式为textLabel赋予价值,所以在你的SecondViewController
中以这种方式为该标签赋值:
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
var textlbl = String()
override func viewDidLoad() {
super.viewDidLoad()
self.titleLabel.text = textlbl
}
}
HERE我为您提供了一个示例项目供您参考。