Wednesday, July 27, 2016

Brief Introduction to iOS Development - Part 10 - Understand View Controller Life Cycle and Model View Controller Design

In this session, we will be looking into View Controller life cycle and then later at the MVC programming model which iOS used.

In every app we created, there are some default program that was pre-written. The first program is AppDelegate.swift. This program serve as the entry point of an app. It is the first level program of an app. AppDelegate will create a window and loop the app for events.

The next piece of default code is ViewController.swift. View controller is responsible for drawing and controlling the view layout in the window. An app has only one window, however, an app can have multiple views and view controllers. Therefore, we need to specified which view controller is the main entry point if we are using more than one view.

View controller will load its program to the memory and display the view on the device. During this transition, we are given several entry point to include program before the view appear and after the view appear. Within view controller class, we are given several function/program to work on while the transition happen.

We have the following function:
  • viewDidLoad
  • viewWIllAppear
  • viewDidAppear
  • viewWillDisappear
  • viewDidDisappear

We will be discussing the first 3 function as it is more commonly used.

viewDidLoad program will start executing when the view elements and its program are loaded into the memory. We can include any initialization program here. If we want to program or add any view element programmatically, we can do so here. On our previous program, we initialize the textfield delegate here.

viewWillAppear will start executing when all the instruction in viewDidLoad are executed and before the visual element start to appear. We can include any program we want just before the visual element start appearing. We usually include program to populate the data into view element such as label here.

viewDidAppear will start executing after the view appear. Usually we include background program that is more CPU intensive and take more time to process such as network connection.

In a MVC (Model-View-Controller) programming model, we separate our program into 3 portion. The model refers to data model. This means that when we code, we need to separate the data from view and controller. This is a good arrangement because we can change the view and view controller without touching the data.

The view portion is responsible for the display of the UI and data. The view portion will not involve in handling of data.

Controller is the link between data and view. Controller will query data from the data model and transfer such data to the view. Depends on the program, view controller might need to involved in computation and even drawing visual object.

Now let's start a new project as follows:


Let's called the program "Intro10"


We need to populate the storyboard with the following element in order: textfield, button, label, button and label.

For the textfield, please refer to the settings as shown below:


The auto layout for the textfield is as follows:


For the first button, the setting is as below:


The auto layout settings is as below:


The first label settings is as follows:


The auto layout is as follows:


The second button settings is as follows;


The auto layout of second button is as follows:


The settings of second label is as follows:


The auto layout of second label is as follows:


Once the layout is done, we can start linking the UI to view controller. First switch to assistant editor mode.


Then we need to drag the textfield and the 2 labels to view controller. We name the textfield as myName, the first label as myStatus and last label as myLastName.


Please note that we want user to enter name to the textfield. The label myStatus will display how names we have entered. The last label will display the latest name we have entered.

Now, lets prepare to link button. Before that, we create another section known as Action at the end just before the last closing braces.


Next, we link the first button as follows:


Please note that we always need to link the button as action. The next button should be link as follows:


The result should be similar to the code as shown below:


Now, we can switch back to standard editor mode.


Actually, this is a simple program. Therefore, there is no need to separate data with controller. However for demonstration purpose, we will be creating a separate code for data.

Create a new file as shown below:


Under iOS, select Source -> Swift File


Name the swift file. In this example, we just named "data.swift"


A separate Swift file will be created as shown below:


We just need to enter the following code:

var nameList = [String]()



The code above is an array of strings. Thats all for the data model. For more complex data model such as classes we definitely need a separate file.

Since, we are using textfield, we would like to add UITextFieldDelegate as shown below:


Then we need to initialize the textfield delegate in the viewDidLoad function:


We just need of the helper program textFieldShouldReturn as follows:


    // MARK: UITextFieldDelegate
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        textField.resignFirstResponder()
        
        return true
    }

The screen shot is as follows:



Now, we need to override viewWillAppear as shown below:



    override func viewWillAppear(animated: Bool) {
        
        myStatus.text = "Total = " + String(nameList.count)
        
    }

Alternatively, we can do without viewWillAppear and just include the statement in viewDidLoad program. If your viewDidLoad program is pack with code, then it is advisable to use viewWillAppear.


Now we can populate the button action program. For addName button use the following code:


    @IBAction func addName(sender: UIButton) {
        
        myName.resignFirstResponder()
        
        let tempName = myName.text ?? ""
        
        if !tempName.isEmpty {
            
            nameList += [tempName]
            myStatus.text = "Name Saved! " + "Total = " + String(nameList.count)
            
        } else {
            
            myStatus.text = "Cannot Save Empty Name! " + "Total = " + String(nameList.count)
        }

    }

The first line of the program is to hide the keyboard if it is not hidden. The second line is to check the textfield and assign the text to a temporary name. Finally, we have a conditional branch to check if the temporary name is empty. If it is not empty then we add the text to the string array and update the status label. If the temporary name is empty, we just need to update the status label.

The screen shot is as follows:


The program for displayLastName is as follows. Please note that displayLastName here refers to display the last name entry.


    @IBAction func displayLastName(sender: UIButton) {
        
        myName.resignFirstResponder()
        
        if nameList.count > 0 {
            
            let displayName = nameList.last!
            myLastName.text = "The last name in the list is " + displayName
            
        } else {
            
            myLastName.text = "The last name in the list is No Name"
        }
        
    }


As usual, the first line of the code is to hide the keyboard if it is not hidden. Then, we need to check the number of item in the string array. If there is one or more item in the array, we extract the last item in the array and display the text to the second label.

The screen shot is as follows:



A copy of this project is stored at Github https://github.com/SwiftiCode/Intro10

*** End ***

No comments:

Post a Comment