我已经创建了一个使用Storyboard来展示新页面或类的简单应用程序。然而,我希望通过编程方式实现相同的功能。
我的初始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)
}
当我按下按钮时,我收到以下错误:
终止应用程序,原因是未捕获的异常'NSInvalidArgumentException',原因是:'故事板()不包含标识符为'SelectionScreen'的视图控制器'
我使用Cocoa Touch Class创建了下一个视图控制器:
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 :)”可以加载我想要查看的新类。如果不使用Storyboard,我该如何为SelectionScreen类提供标识符?
let selectionScreen = SelectionScreen()
然后执行present
方法。 请提供更多细节。