如何通过代码打开弹出窗口

How to open pop up via code

我是一个非常新手 swift 的程序员,他正在尝试执行以下操作:我有一个简单的游戏,它通过按下某些按钮来生成弹出窗口(通过单独的视图控制器)。我还想添加一些代码(在某些事件后 运行s)在特定条件下打开弹出窗口。为此,我创建了一个新的视图和视图控制器并将它们链接起来。整个视图控制器如下所示:

import UIKit

class P2_Gift_Pop_Up: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print("I was here")

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }   
}

现在我尝试在主 viewcontroller 的代码中使用以下行来调用此视图控制器(以弹出视图):

P2_Gift_Pop_Up()

Swift 接受这个但是当我 运行 应用程序没有任何反应。我做错了什么?

class MainViewController: UIViewController {

    let button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        // setup button frame or constraint.. (unless done in IB)

        // add target to button (or add an IBOutlet from IB)

        button.addTarget(self, action: #selector(buttonClicked(_ :)), for: .touchUpInside)
    }

    @objc func buttonClicked(_ sender: UIButton) {
        let vc = P2_Gift_Pop_Up()
        vc.modalPresentationStyle = .overCurrentContext
        present(vc, animated: true, completion: nil)
    }
}

P2_Gift_Pop_Up VC 里面:

class P2_Gift_Pop_Up: UIViewController {

    let dismissButton = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        // setup button frame or constraint
        // ..

        // add target to button

        dismissButton.addTarget(self, action: #selector(buttonClicked(_ :)), for: .touchUpInside)
    }

    @objc func buttonClicked(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}

在 viewController 中调用 P2_Gift_Pop_Up() 不会显示它,在您的情况下模态显示效果很好,因为您希望 P2_Gift_Pop_Up() 弹出。

因为我不想使用按钮,所以我只在主视图控制器中使用了以下代码片段。

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

这将在弹出窗口 window 中启动 运行ning 代码,没有任何按钮,即我想要的。

但是,当我运行下面的代码

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()

}

}

我收到以下错误:线程 1:致命错误:在展开可选值时意外发现 nil

怎么了?我在主视图控制器中使用按钮打开的弹出窗口中的相同代码有效。

Ps。抱歉,如果将此作为我自己问题的答案发布是解决此问题的错误方法(当我包含代码时,评论变得不可读,编辑原始问题会改变我最初想知道的内容,我确实回答了我最初的问题想知道)