试图在上一个视图控制器上更新UI时崩溃

发布于 2025-02-06 22:50:33 字数 972 浏览 1 评论 0原文

好吧,我有视图控制器A呈现查看控制器B,就像这样...

@IBAction func presentView(_ sender: Any) {
    let storyBoard : UIStoryboard = UIStoryboard(name: "main", bundle:nil)
    let vc = storyBoard.instantiateViewController(withIdentifier: "Popout") as! PopoutWindow
    vc.modalTransitionStyle = .coverVertical
    vc.modalPresentationStyle = .overFullScreen
    self.present(vc, animated:true, completion:nil)
}

完成视图控制器B时,我会像这样将其视为...

let vc = WellnessPlanEnrollmentController()
self.dismiss(animated: true, completion: {
vc.refreshView()
})

然后我所呼叫的功能正在尝试使用该功能更新我的UI来自View ControllerB的新数据B。但是,当我重新加载第一个视图时,我会遇到一个奇怪的崩溃,说我要更新的标签是无。

func refreshView() {
    DispatchQueue.main.async {
        self._petNameLabel.text = self.object.name
        // crashes here because my label is nil???????
    }
}

错误:firstViewController.swift:128:致命错误:意外发现的同时暗中解开可选值

我觉得这是因为当我调用函数时,视图不在焦点当然。

Alright I have view controller A that presents view controller B like so...

@IBAction func presentView(_ sender: Any) {
    let storyBoard : UIStoryboard = UIStoryboard(name: "main", bundle:nil)
    let vc = storyBoard.instantiateViewController(withIdentifier: "Popout") as! PopoutWindow
    vc.modalTransitionStyle = .coverVertical
    vc.modalPresentationStyle = .overFullScreen
    self.present(vc, animated:true, completion:nil)
}

When I'm done with view controller B, I dismiss it like so...

let vc = WellnessPlanEnrollmentController()
self.dismiss(animated: true, completion: {
vc.refreshView()
})

And then the function I'm calling is attempting to update my UI with the new data from view controller B. However, when I reload the first view, I get a weird crash saying that my label I'm trying to update is nil.

func refreshView() {
    DispatchQueue.main.async {
        self._petNameLabel.text = self.object.name
        // crashes here because my label is nil???????
    }
}

Error: FirstViewController.swift:128: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I feel like it's because the view is not in focus when I'm calling the function but I'm not sure.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执笔绘流年 2025-02-13 22:50:33

这是失败的,因为您创建了wellnessplanenrollmentController的新实例。此实例没有连接到任何故事板或查看,因此其所有插座都是零。

可能的解决方案:

在您的控制器b中创建一个委托,然后在介绍之前将其分配并在解雇后调用。

This is failing because you create a new instance of WellnessPlanEnrollmentController. This instance is not connected to any Storyboard or View so all of its outlets are nil.

Possible solution:

Create a delegate in your controller B and assign it before presenting and call it after dismiss.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文