Search code examples
buttoncontrollernavigationswiftback

Button Action to Controller and Back Swift


I am new to programming Swift and I have a Button with a Target to a function:

func buttonAction(sender:UIButton!)
{
    self.window.rootViewController.presentViewController(FirstViewController(), animated: true, completion: nil);

}

Yet, I have a Button on the FirstView (of FirstViewController) and yet I want to go back to the MainView (of MainViewController) and I get the error Code:

2014-07-30 00:53:44.545 FifthTry[30275:833440] Warning: Attempt to present
<_TtC8FifthTry19FirstViewController: 0x787b5470> on <_TtC8FifthTry18MainViewController:
0x799802d0> whose view is not in the window hierarchy!

What is wrong?


Solution

  • It is great that you split your code into a separate View and Controller class. This is great class design. However, your controller is the one that should handle touch events according to Model-View-Controller which is the paradigm that Apple's frameworks use. The view is for displaying data and the controller is for handling user interaction on that view. If you setup the action on your controller, presenting a view controller is extremely easy because that is the way that Apple encourages you to break down your classes:

    func buttonAction(sender:UIButton!)
    {
        self.presentViewController(FirstViewController(), animated: true, completion: nil)
    }