我正在以编程方式在Swift 5中构建游戏,并希望从主菜单导航至游戏屏幕。这是我的代码:
func handleButtonsTapped() {
playButton.addTarget(self, action: #selector(pushGameViewController), for: .touchUpInside)
}
和选择器在点击时处理推视图控制器:
@objc func pushGameViewController() {
let destinationVC = GameViewController()
navigationController?.pushViewController(destinationVC, animated: true)
}
当我点击模拟器中的按钮时,没有任何反应。我在handleButtonsTapped()
函数中也调用了viewDidLoad()
。
这是我的代码,可以运行。
您是否为UINavigation设置了ViewController?
@IBOutlet weak var playButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
handleButtonsTapped()
}
func handleButtonsTapped() {
playButton.addTarget(self, action: #selector(pushGameViewController), for: .touchUpInside)
}
@objc func pushGameViewController() {
let destinationVC = GameViewController()
navigationController?.pushViewController(destinationVC, animated: true)
}
得到答案!
在我的SceneDelegate.swift
中设置:
let menuViewController = UINavigationController(rootViewController: MenuViewController())
window?.rootViewController = menuViewController
现在可以了!谢谢大家的评论:)
您无法直接初始化情节提要视图控制器出口。而是可以从发生情节提要的包中加载它。请按照以下步骤操作。
然后用下面的内容替换pushGameViewController函数。
@objc func pushGameViewController() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationVC = storyboard.instantiateViewController(withIdentifier: "GameViewController")
self.navigationController?.pushViewController(destinationVC, animated: true)
}
@objc func pushGameViewController() {
let destinationVC = storyboard.instantiateViewController(withIdentifier: "GameViewController") as! GameViewController
navigationController?.pushViewController(destinationVC, animated: true)
}
请确保在界面构建器中为视图控制器提供一个名为GameViewController
的故事图板ID