xcode - 准备继续查看 Controller 时发生 fatal error

标签 xcode swift uilabel segue

我目前在 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/

相关文章:

ios - 导航栏在 iOS 应用程序中位于状态栏下方

objective-c - 添加方法后应用程序无法启动(Xcode 7.2)

ios - 如何忽略 codable 中的 nil json 值

ios - 为什么选项卡式应用程序中缺少核心数据选项?

ios - UITapGestureRecognizer 无法在自定义类内部工作(这不是 View Controller )

iphone - 音频处理期间的标签更新

ios - 使用 Xamarin Studio 在 iOS 中实现 'About' View

ios - 如何将静态元素添加到 UICollectionViewController 或使它们与其共享同一屏幕

ios - 静态部分/单元格的 UITableView 背景图像

iOS 标签即使在主线程中也不会更新文本