Reputation: 37
I'm building a game in Swift 5 programmatically and want to navigate from the main menu to the game screen. Here is my code:
func handleButtonsTapped() {
playButton.addTarget(self, action: #selector(pushGameViewController), for: .touchUpInside)
}
And the selector to handle pushing the view controller when tapped:
@objc func pushGameViewController() {
let destinationVC = GameViewController()
navigationController?.pushViewController(destinationVC, animated: true)
}
When I tap the button in simulator nothing happens. I have handleButtonsTapped()
called in my viewDidLoad()
function as well.
Upvotes: 1
Views: 4113
Reputation: 151
@objc func pushGameViewController() {
let destinationVC = storyboard.instantiateViewController(withIdentifier: "GameViewController") as! GameViewController
navigationController?.pushViewController(destinationVC, animated: true)
}
Be sure to give your view controller a storyboard id called GameViewController
in the interface builder
Upvotes: 1
Reputation: 924
You can not initialize a storyboard view controller outlet directly. Rather you can load it from the bundle where your storyboard takes place. Follow this belowing steps.
Then replace the pushGameViewController function by the below one.
@objc func pushGameViewController() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationVC = storyboard.instantiateViewController(withIdentifier: "GameViewController")
self.navigationController?.pushViewController(destinationVC, animated: true)
}
Upvotes: 1
Reputation: 37
Got an answer!
In my SceneDelegate.swift
I set:
let menuViewController = UINavigationController(rootViewController: MenuViewController())
window?.rootViewController = menuViewController
Now it works! Thanks for the comments everyone :)
Upvotes: 1
Reputation: 11
This is my code and this can running.
Is your ViewController set for UINavigation?
@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)
}
Upvotes: 0