我目前在 destViewController.titleLabel.text = "Testing Segue"处遇到 fatal error ,在展开可选值时意外发现 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"
}
}
}
最佳答案
首先在 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我创建了一个示例项目供您引用。
关于xcode - 准备继续查看 Controller 时发生 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28640685/