IBOutlet 未初始化 [英] IBOutlet is not initialized

查看:41
本文介绍了IBOutlet 未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

xcode 有一些奇怪的地方.突然间,普通的流动被打破了.为了检查它,我创建了一个只有两个 viewController 的新项目.第一个(命名为 ViewController)只包含一个按钮来打开第二个(命名为 NewViewController)控制器,它包含唯一的 UILabel.

there is something strange with xcode. Suddenly the ordinary flow is broken. To check it I've created a new project with just two viewControllers. First (named ViewController) contains only one button to open the second (named NewViewController) controller, which contains the only UILabel.

import UIKit

class ViewController: UIViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "Show New View" {
            guard let newVC = segue.destination as? NewViewController else { return }

            newVC.passedText = "some abstract text"
        }
    }
}

import UIKit

class NewViewController: UIViewController {
    @IBOutlet weak var myLabel: UILabel!

    var passedText: String? {
        didSet {
            guard let text = passedText else { return }

            myLabel.text = text
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

main.storyboard 看起来如此

IBOutlet 连接良好

但调试器显示 UILabel 为零

我做错了什么?

推荐答案

不,没有任何问题.你就是那个做错的人.在您调用 newVC.passedText = "some abstract text" 时,newVC 尚未加载其视图,其出口仍然 nil.所以设置 myLabel.text 的调用发生在插座确实仍然是 nil 的时候.

No, nothing has "broken". You're the one who is doing it wrong. At the time you are calling newVC.passedText = "some abstract text", newVC has not yet loaded its view and its outlets are still nil. So the call to set myLabel.text is happening at time when the outlet is indeed still nil.

您的错误是您过早地尝试配置 myLabel.将值存储在 newVC 中,是的.但至于设置myLabel.text,等到viewDidLoad,当视图和插座工作时.

Your mistake is that you are trying to configure myLabel too soon. Store the value in newVC, yes. But as for setting myLabel.text, wait until viewDidLoad, when the view and outlets are working.

因此,正确的模式如下所示:

The correct pattern, therefore, looks like this:

var passedText: String? {
    didSet {
        guard let text = passedText else { return }
        myLabel?.text = text
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    guard let text = passedText else { return }
    myLabel?.text = text
}

现在,无论 when passedText 相对于 viewDidLoad 的设置如何,您的代码都会做正确的事情.

Now your code does the right thing regardless of when passedText is set in relation to viewDidLoad.

这篇关于IBOutlet 未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆