ストーリーボードを使用して新しいページ/クラスを表示する簡単なアプリをすでに作成しました。ただし、プログラムで同じことをしたいと思います。
私の最初の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 TouchClassを使用して次の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.
}
}
ストーリーボードで最初にこれを行ったとき、Identity Inspectorを使用してストーリーボードIDを設定し、instantiateViewController(withIdentifier :)が表示したい新しいクラスをロードできるようにしました。ストーリーボードを使用せずに、SelectionScreenクラスの識別子を提供するにはどうすればよいですか?
ストーリーボードを使用していない場合は、識別子は必要ありません。インスタンス化して提示するだけです。
let loadVC = SelectionScreen()
self.present(loadVC, animated: true, completion: nil)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加