xcode IBOutlet未初始化

zdwk9cvp  于 2023-02-25  发布在  其他
关注(0)|答案(3)|浏览(108)

xcode有一个奇怪的地方。突然之间,普通的流程被打破了。为了检查它,我创建了一个只有两个viewController的新项目。第一个(名为ViewController)只包含一个按钮来打开第二个(名为NewViewController)控制器,它包含唯一的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()
    }
}

the main.storyboard looks so
IBOutlet is well connected
But the debugger shows what the UILabel is nil
我做错了什么?

np8igboo

np8igboo1#

不,没有任何东西“坏了”。你才是做错的人。在你调用newVC.passedText = "some abstract text"时,newVC还没有加载它的视图,它的插座仍然是nil。所以调用set myLabel.text发生在插座确实仍然是nil的时候。
你的错误是你试图配置myLabel太快。存储值在newVC中,是的。但至于设置myLabel.text,等到viewDidLoad,当视图和插座工作。
因此,正确的模式如下所示:

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
}

现在,无论 * passedText何时相对于viewDidLoad设置,您的代码都会执行正确的操作。

fv2wmkja

fv2wmkja2#

你需要在故事板的视图控制器的标识检查器中设置定制类NewViewController,也许你忘了这么做?

ckx4rj1h

ckx4rj1h3#

当我从SceneDelegate初始化我的UIViewController时,如果我像这样初始化我的UIView控制器,我会遇到同样的问题:

window = UIWindow(windowScene: winScene)
let navigationController = UINavigationController()
        navigationController.pushViewController(
            MyViewController(), animated: false)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()

@IBOutlet变量viewDidLoad函数中为空,但如果我使用如下脚本初始化它:

let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil);
let initViewController = storyboard.instantiateViewController(withIdentifier: "MyViewController") as UIViewController
window = UIWindow(windowScene: winScene)
let navigationController = UINavigationController()
navigationController.pushViewController(
            initViewController, animated: false)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()

然后,所有**@IBOutlet变量将在viewDidLoad**函数中初始化。

相关问题