Sunday, April 17, 2016

Swift Tutorial - Part 5 - View Lifecycle

View and Controller communications and View Lifecycle



Video Description 

View and Controller communication

In the Model View Controller design pattern we have communications between View and Controller. If Controller wants to send message to the view, it uses IBOutlet. If View wants to send message to the controller that for example some button pressed or the slider has changed it uses IBAction.

View Lifecycle

A series of methods that are sent to the View Controller when things happened. For example if we want to initialize some parameters before view appears to the user, we should use view lifecycle methods. Using these methods means overriding them. Because we override these methods, the first line of each method we should call the super (super class) and the name of the method. Here are the important view lifecycle methods:

viewDidLoad

The most important view lifecycle method is this method. This is a great place for initialization because it will be called only one time during the whole lifecycle and also all outlets are set. But do not initialize things that are related to geometry because at this point we can't be sure if we are on iPhone 5 size or 4 or iPad ...
override func viewDidLoad() {
        super.viewDidLoad()
        //Do one time initializations
    }

viewWillAppear

This method is called each time that the view appears to the screen so it's not a good place for initialization because it could be called more than one time during the lifecycle. But it's a good place for updating the view.
override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //Do updating the view and geometry settings
    }

viewWillDisappear

This will be called a moment before view disappear from the screen. This is a good place to save the data to the storage. For example remembering the scroll position or saving what user typed so far, in order to retrieve it once s/he comes back to the view.
override func viewWillDisappear(animated: Bool) {
        super.viewWillAppear(animated)
        
    }

No comments:

Post a Comment