首页 > 解决方案 > Swift:无法修改弹出窗口中的图像

问题描述

初学者 swift-user 在这里。我想从主视图控制器打开一个连接到单独视图控制器(P2_Gift_Pop_Up)的弹出窗口。为此,我在主视图控制器的代码片段中包含以下内容

let vc = P2_Gift_Pop_Up()
vc.modalPresentationStyle = .overCurrentContext 
present(vc, animated: true, completion: nil)

这开始在弹出窗口中运行代码(打印语句仍然有效),到目前为止,一切都很好。

但是,当我尝试修改连接到视图控制器的视图中的某些元素时,我得到一个

线程 1:致命错误:在展开可选值时意外发现 nil。这是完整的代码。

import UIKit

class P2_Gift_Pop_Up: UIViewController {

    @IBOutlet weak var Slot1: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        Slot1.setImage(UIImage(named: "Card 2 Red"), for: .normal)
    }

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

尽管我(通过本网站上的另一个答案)了解味精的含义,但我不明白为什么我会在这种情况下得到它,以及如何解决它。还可能需要强调的是,尽管代码在 P2_Gift_Pop_Up 调用之后开始运行,但未显示相应的视图。

标签: iosswiftxcodepopupuikit

解决方案


您需要像这样展示您的控制器(您需要设置故事板 ID,然后将其添加到标识符中):

    let storyBoard = UIStoryboard(name: "main", bundle: Bundle.main)
    let vc = storyBoard.instantiateViewController(withIdentifier: "your storyboard id") as! P2_Gift_Pop_Up
    vc.modalPresentationStyle = .overCurrentContext
    present(vc, animated: true, completion: nil)

由于您的按钮(Slot1)没有内存,您的应用程序正在崩溃,因此您需要像上面一样呈现。


推荐阅读