0

I have just started working with swift, i have created a subview which has a button on it, i would like to use that button to take me to my mainviewcontroller.

i have used same functionality for a different button however having a function in same file allows that button to work the code is below

var playAgainButton = UIButton(frame: CGRectMake(0, 150, 320, 40))
            playAgainButton.setTitle("Play Again", forState: UIControlState.Normal)
            playAgainButton.addTarget(self, action: Selector("startGame"), forControlEvents: UIControlEvents.TouchUpInside)
            playAgainButton.backgroundColor = UIColor.redColor()
            gameOver.addSubview(playAgainButton)

is it possible to use similar code to navigate to a different viewcontroller?

Thanks

chirag90
  • 2,061
  • 1
  • 19
  • 34

1 Answers1

1

Are you using storyboards, or is this all in code? If it's in code, create a method like

func goToMainVC() {
    if let navController = self.navigationController {
        navController.popToRootViewControllerAnimated(true)
    }
}

and set the button's target to a selector that calls it.

If you're using storyboards, you have three options:

  1. ctrl+drag a connection from your button back to the main view controller (easy, but bad form because it just pushes the main VC back onto the nav controller);
  2. Add @IBAction before the fun goToMainVC() method above, then ctrl+drag a connection from your button to the view controller in which it's contained, and then select that outlet method (this is how most people would do it); or
  3. The best option is to use an unwind segue, as described here.
Community
  • 1
  • 1
NRitH
  • 11,597
  • 4
  • 36
  • 40
  • its all in a code, i have just tried the goTo function, but when i click on home it doesnt do anything. – chirag90 Sep 18 '14 at 21:48
  • 1
    Hi Sorry i have now solved the issue, it was me who wasnt looking at the storyboard, i had to add a navigation controller, i did po self.navController anf found it was passing nil so went in the storyboard added a navigation controller and it started working. For fast response NRitH – chirag90 Sep 19 '14 at 18:02