以编程方式在 swift/programmatically 中呈现一个新的视图控制器给 class 一个标识符

programmatically present a new view controller in swift/programmatically give a class an Identifier

我已经创建了一个简单的应用程序,它使用故事板来呈现新的 page/class。但是,我想以编程方式做同样的事情。

我的初始 ViewController.swift 文件如下所示:

import UIKit

class ViewController: UIViewController {


    var mainImageView: UIImageView!
    var chooseButton: UIButton!
    var nameLabel: UILabel!

    override func loadView() {
        view = UIView()
        view.backgroundColor = .white

        let chooseButton = UIButton(type: .custom) as UIButton
        chooseButton.backgroundColor = .blue
        chooseButton.layer.borderColor = UIColor.darkGray.cgColor
        chooseButton.layer.borderWidth = 2
        chooseButton.setTitle("Pick a side", for: .normal)
        chooseButton.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
        chooseButton.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
        chooseButton.layer.cornerRadius = chooseButton.frame.size.height/2
        self.view.addSubview(chooseButton)

        self.nameLabel = UILabel()

        nameLabel.text = "Here is your side"
        nameLabel.textAlignment = .center
        nameLabel.backgroundColor = .cyan
        nameLabel.frame = CGRect(x: 100, y: 400, width: 200, height: 100)
        self.view.addSubview(nameLabel)


    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    @objc func clickMe(sender:UIButton!) {
        print("Button Clicked")
        self.nameLabel.text = "updated title"
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let loadVC = storyBoard.instantiateViewController(withIdentifier: "SelectionScreen") as! SelectionScreen
        self.present(loadVC, animated: true, completion: nil)


    }

当我按下按钮时,我收到以下错误:

terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Storyboard () doesn't contain a view controller with identifier 'SelectionScreen''

我使用 Cocoa Touch Class 创建了下一个 Viewcontroller:

import UIKit

class SelectionScreen: UIViewController {


    override func loadView() {
        view = UIView()
        view.backgroundColor = .red




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

        // Do any additional setup after loading the view.
    }



}

当我最初对 Storyboard 执行此操作时,我使用 Identity Inspector 设置 Storyboard ID,以便 instantiateViewController(withIdentifier:) 可以加载我想查看的新 class。如何在不使用 Storyboard 的情况下为 SelectionScreen class 提供标识符?

如果您不使用故事板,则不需要标识符。只需实例化并呈现即可。

let loadVC = SelectionScreen()
self.present(loadVC, animated: true, completion: nil)