按下按钮时推新视图控制器

问题描述 投票:0回答:4

我正在以编程方式在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()

ios swift uinavigationcontroller swift4 swift5
4个回答
0
投票

这是我的代码,可以运行。

您是否为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)
}

0
投票

得到答案!

在我的SceneDelegate.swift中设置:

let menuViewController = UINavigationController(rootViewController: MenuViewController())
window?.rootViewController = menuViewController

现在可以了!谢谢大家的评论:)


0
投票

您无法直接初始化情节提要视图控制器出口。而是可以从发生情节提要的包中加载它。请按照以下步骤操作。

  1. 首先设置Storyboard ID'GameViewController'(根据屏幕截图)。
  2. 然后用下面的内容替换pushGameViewController函数。

    @objc func pushGameViewController() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let destinationVC = storyboard.instantiateViewController(withIdentifier: "GameViewController")
        self.navigationController?.pushViewController(destinationVC, animated: true)
    }
    

enter image description here


0
投票
@objc func pushGameViewController() {
    let destinationVC = storyboard.instantiateViewController(withIdentifier: "GameViewController") as! GameViewController
    navigationController?.pushViewController(destinationVC, animated: true)
}

请确保在界面构建器中为视图控制器提供一个名为GameViewController的故事图板ID

© www.soinside.com 2019 - 2024. All rights reserved.