How to Use Container View Controller

Container View Controller is one of the interesting View Controllers that I used recently in XCode. Apple has provided many standard view controllers for iOS Developer in XCode such as Table View Controller, Tab Bar Controller, Navigation View Controller for most common standard projects for iOS developers. But for a certain projects with unique design, we have to use container view controller.

I have been using container view controller for a while and I love it. Here is a simple guide on how to use it. I will create a simple mobile app with 3 different view controllers:-

Simple Container View Controller Programming Example

1. MainVC
2. ProfileVC
3. Menu VC

Description
– Contain a navigation with 2 buttons.
– When the Profile button is clicked, the MainVC will slide to left and the ProfileVC will appear.
– When the Menu button is clicked, the Main VC will slide to right and the MenuVC will appear.

Profile View controller
Main View controller style=
Menu View controller


Container View Controller Project Setup

Update: I have been busy for the last few months, just updated this post on February 2014.

Step 1: Create a new project and delete the existing .h and .m file that was created by the XCode

Step 2: Create the subclasses below:-
MainVC, MenuVC, ContainerVC and ProfileVC subclass of UIViewController
ShareSetting subclass of NSObject

Step 3: Link the existing view controller objects on storyboard with ContainerVC.

Step 4: Drag and drop the Container View in storyboard into the ContainerVC View Controller object. Rename this Container View as “MenuVC”. The position and side for this container view should be X: -260 Y: 20 Width: 320 Height: 548. Attach the MenuVC subsclass to the view controller comes with the Container View.

Step 5: Drag and drop another Container View into the same view controller and name it as “ProfileVC”. X: 260 Y: 20 Width: 320 Height: 548. Remember to attach ProfileVC subclass to the created view controller.

Step 6: Drag and drop the last Container View and name it as “MainVC”. X: 0 Y: 20 Width: 320 Height: 548. Attach the subclass to the view controller.

Step 7: Change background for each view controller object (MainVC, MenuVC and ProfileVC) to different colors.

Step 8: Add a title to MenuVC and ProfileVC

Step 9: Add a simple navigation bar and 2 buttons to MainVC.

If you are doing correctly, you should see a screen shot similar to below:
Simple Container View Controller Programming Setup

Container View Controller Coding

1. ShareSetting
– This class is basically used to share actions/behavior for the same buttons across a few different view controllers. Although in this simple project, we only have 1 view controller that uses the buttons. In more complex projects, we usually need this ShareSetting. Add the following codes to the class.

In ShareSettings.h

In ShareSettings.m

2. ContainerVC
– This is the main class that control the animation behavior for 3 different view controllers (MainVC, MenuVC and ProfileVC)

In ContainerVC.m

3. MainVC
– This is the Main View Controller which contains the navigation bar, the Menu Button and Profile Button.
– The 2 buttons that were created on the storyboard should be “Control + Drag” into the subclass. So that there will be 2 functions created in the subclass and every time the button is tapped, we will receive the action in the functions.

Last Step: You are done! For your information, the MenuVC and ProfileVC subclasses are created but there is no function for this simple example. You may add tableview to MenuVC and create a real profile for ProfileVC by adding some text field, photo and etc.

For more information, you can check Out: View Controller Programming Guide for iOS

Go-Eco – Mobile Application That Rewards Anyone Who Helps the Environment

I was at the Global Startup Youth organized by Startup Malaysia. This event was attended by over 500 youth from over 60 countries who are either developers, hustlers, domains experts or youth leaders. The youth was helped by over 100 mentors to solve some of the world biggest problems using mobile applications in 2 days time. There are 4 categories: Environment, Education, Health and Women Empowerment.

I was in Team 4 under the Environment category and I am the main coder. Our team consists of mostly Malaysian with 1 person from Morocco, another from Russia and the last one from West Africa (Sierra Leone).

We came out with a mobile app idea with the following features:-
1. Educate users related to environmentally issue
2. Encourage people to take actions to help the environment
3. People will gain points from the actions they take or the education that they learn.

The points that they gain from the mobile app can be used to exchange for vouchers by our sponsors such as (Starbuck, YTL, Old Town Kopitiam, Machines and etc). Our team leader went to talk to a few reputable companies and some of them are interested to join this project as part of their corporate social responsibility. But, the deal does not materialised yet as we only have 2 days. Shall the project continues in the future, I believe we really will have the real sponsor vouchers.

Please allow me to introduce you: Go-Eco. The app is using Parse.com as the backend server. Go-Eco has the following screens:-
1. Login
2. Sign Up
3. Profile
4. Learning
5. Challenges
6. Redemption

Most of the functions of the app are already completed. We have the real login and sign up (connect to Parse). The points addition and reduction (for completing learning, challenges and redemption)

The followings are the real screen shots from the app itself.
Go-Eco Login Go-Eco Sign Up

Go-Eco ProfileGo-Eco Learning

Go-Eco LearningGo-Eco Learning

Go-Eco ChallengesGo-Eco Challenges

Go-Eco ChallengesGo-Eco Redemption

Go-Eco Redemption

It has been a nice experience working with Team 4. They are really focused and committed. We are also lucky to have a great graphic designer in our team. Unfortunately, we didn’t win under the environment category, the judges certainly have different opinions on what they think is the best app under the environment category. Winning is not the main purpose here. It is the team work and our effort to produce something that will help this world.

Lastly, I am very happy the mobile app that we produced in just 2 days time. It is functional and very polished. We shall see if we are able to bring Go-Eco forward.

Simple Calculator iOS Application

The First assignment that I did when following the Stanford iPhone / iPad Development course was the Simple Calculator iOS Application. In this post, I am going to share every step in making this mobile application.

Create a New Project

First of all, launch the Xcode and create a new project using “Single View Application“.
null

Under Product Name, you may put “Calculator”. Put your name or your company’s name under organization name.

As for Company Identifier, it is usually the reverse characters of a web domain that you own. For example, if you own “abc.com” then you put it as “com.abc”. If you do not own any web domain, you can just put any domain such as “com.example”. It is not important for now if you just want to run the application on simulator. But, when you want to run the application on your mobile device, you should get your own domain. You will also need to do some provisioning settings on the Apple Developer Portal, attach the provisioning certificates on your Xcode before you can run it on your device and also submit the application to Apple. I will do tutorial on that in a later post)

Under the Class prefix, you can put it as “Calculator”. Choose “Universal” under Devices as we will build both iPhone and iPad app. Tick “Use Storyboards” and “Use Automatic Reference Counting (ARC)“. We want to use Storyboard as it is an important technology that simplifies the implementation of MVC in iOS. Before iOS 5, the developers have to take care of every object creation and destruction to manage the memory. But, Apple has released a new technology calls ARC which simplifies the memory management in Xcode.

After you click “Next”, you will be asking to choose a place that you want to create this project. I normally put it under a “Developer” folder just to keep everything organized. After you click “Create”, you will see a screen like the below screen shot:-

Your project will have 2 AppDelegate files (.h, .m), 2 storyboards (for iPhone and iPad) and 2 ViewController files (.h, .m). .H is a header file which can be accessed by public while .M is a implementation file which can only be accessed by the class itself (private).

The storyboards will contain all the views for our controllers. So, the initial project creation has given us both the view and also controller. We will create our own model later.

Creating Our Views

We will leave iPad storyboard for now until the end of the tutorial. So, let’s start with the iPhone storyboard. From the storyboard, you will see an iPhone size view controller object on the screen. When you click the “view” inside the view controller object, you may see the height for the view is 548. It is actually the iPhone 5 size. We can click a small screen toggle button on the bottom of the page to toggle it to normal iPhone height which is 460. We will optimize for iPhone 5 later. But for now, we just want to keep it simple and start with normal iPhone size.

How to Implement MVC in iOS Using Xcode

If you have just started to learn iOS Application programming, Some of the questions that come to your mind could be: “What is the best way to program in Xcode IDE?”, “Should I use purely coding? Code + Interface Builder? or Code + Storyboard?”

From my own experience working with some iOS apps developers, I learned that some of them are still using pure coding with some Interface Builder. It means that they haven’t adopt the latest technologies in Xcode provided by Apple. I can not totally blame them, it is because they are developing iOS projects that have been there for a few years and to change everything to the latest technologies is not an easy task to do.

For a fresh new iOS project, it is the best to adopt the latest technologies provided by Apple. It means that we have to use both Code + Storyboard to make the iOS applications.

MVC in Objective-C and Xcode

How do we implement MVC Using Xcode? Here is the quick summary:-

Model: Model is always in coding. It can be in its own class (with .h and .m). But sometimes, we can code a simple Model inside a view controller.
Controller: It always has its own class (with .h and .m). However, Apple has done a great job by making us to be able to see the view Controller in Storyboard. So, we can create a dummy (without function) view controller object on Storyboard. Then, we link this view controller UI Object with our own custom class file (.h and .m). We can code the functions inside the .h and .m files.
View: You can display a view using coding but it is not recommended since the release of storyboard. So, we always create view objects on Storyboard. We just drag and drop the GUI Objects into the View Controller. If we need to have special customization of object, we can subclass that object and manipulate it using code. But most of the time, we do not have to do that as the existing customization properties on the Xcode is already good enough. When a certain objects want to communication with View controller using (Target-Action), we just need to CONTROL drag that element into the .m file. As for Delegate and DataSource, we will implement it on the View Controller files.

Here is the detail explanation on Model, View and Controller with some visual explanations.

If you take a quick look at the Xcode, you will find out that there are many ready to use GUI (Graphic User Interface) Objects such as Button, Text Field, View and even View Controller. You can easily drag and drop the GUI elements into the storyboard. So, Views are mostly available on the storyboard.
View Controller Objects

There are a lot of customization properties inside the view object as well. For Example, you can change the shape of a button, change the title, color, font, image, background image, shadow and more.
UIButton Properties

If you remember the previous post on: Programming in iOS with Objective-C Using MVC, A view can only communicate with view controller using 3 different methods and Target-Action is one of them.

The below are the steps for creating Target-Action for Button to inform the View Controller when the user has clicked the button.

Step 1: Control + Drag the button into the .m implementation file.
Target-Action 1
Step 2: Enter a function Name and also type of sender.
Target-Action 2
Step 3: A function is created and you can start to code the body of the function.
Target-Action 3

For View controller, the below shows the .h and .m files.
dot H and dot M files for view controller

We can always link the custom class (.h and .m) with the view controller object on the storyboard. We can implement various functions using coding.
Custom class in Xcode

Programming in iOS with Objective-C Using MVC

One of the early concepts that I learn from CS193P iPhone Development Course by Stanford University is MVC (Model, View, Controller). MVC is not a programming language. MVC is not a platform. It is a Software Architecture Design Pattern.

When you want to build a house, you will need to hire a construction architect to plan and design the blueprint of the house. The proper planning and designing is very important to make sure that the house will not collapse, to make sure that the resources are used properly and to make sure that the cost is within the budget.

It is the same with any software application development. If you want to build a great software that will not crash frequently, small in size, user friendly and good response time, lesser lines of codes, easy to debug, easy for other programmers to understand, then you will have to develop the software by following a good programming architecture pattern. So, MVC is the Blueprint of a software development project.

Objective-C is built upon Model, View, Controller (MVC) Design pattern. Apple expects all the iOS programmers to follow this programming architecture pattern. If you want to build a simple mobile application, you can easily get away with it without following the exact MVC patterns. But, when you are building a complex app with many features that needs frequent updates, you will run into a lot of trouble. At the end, you will be wasting a lot of time when trying to convert Non-MVC code to MVC code.

So, before starting a new mobile application development project in iOS, you will have to plan properly using MVC.

What is MVC (Model View Controller)?

Like Professor Professor Paul Hegarty mentioned in the lecture. We can consider MVC as 3 different camps.

Model – What your application is about? (Data, Logics, Rules)
Controller – How you present your application (model) to the end users?
View – The interface which the end users see

What is MVC (Model View Controller)?

A Short Explanation on MVC

Controller always sits in between the Model and View. View does not own the data that it displays. View and Model can not have direct interaction with each other. View gets the data from Controller when the Controller implements itself the datasource of the View. The controller normally will get the data from Model before passing it to View. Only Controller have the freedom to initiate the direct communications to View or to Model. View and Model can communicate with Controller using some indirect methods explain below.

View can inform Controller for a certain events in 3 ways:-
a. Target-Action (eG: buttons)
b. Delegate (Will, Did, Should)
c. Data Source (data at, count)

Model can communicate with Controller only through:-
a. Notifications
b. KVO (Key-Value Observing)

MVC Real Application Examples

Example 1: Creating a Simple Calculator App.
a. The logics of calculating the equations is the Model.
b. The number buttons, arithmetic buttons, the result displaying text are the Views.
c. The View Controller sits in the middle of Model and View.

The Simple Flow: The View Controller gets the inputs (via buttons) from the users and send the inputs to the model. The Model will calculate and send the result back to Controller. Lastly, the controller will present the result on screen via a Display view.

Example 2: Building a University Final Exam Result Application.
a. The Model is the database of the results
b. The View is the Table View/List View that shows the name of students, student ID, Grade, CGPA, total marks, Credit hours.
c. The Controller gets the data from database and shows it on the Views.

For this Exam Result Application, we do not need input from the users, we only need to present the data to the users. So, the model is slightly different comparing with the Calculator App. For View and Controller, they are always the same. View handles the interfaces for the end users and Controller handles the interaction between Model and View.

You might ask, why can’t we just show the data directly from Model to View? Why do we have to go through the hassle to create Controller? Answer: It is to make the programming in a simple and manageable way. When we want to troubleshoot a simple bug, we will know exactly where the bug is (either Model, View or Controller). From there, we can easily find the appropriate classes and find the bug from there.

Here is the example MVC Design vs Non-MVC Design:-
As you can see from the following graph,

When MVCs are Working Together:-
Model View Controller Working Together
The above diagram show how the MVCs working together. You can see that the MVCs have simple and manageable flows. Each of the pointers are obeying the MVC rules.

When MVCs are Not Working Together/ Non-MVC:-
Non-Model View Controller
MVCs are not working properly on the above diagram. I just simply call it as Non-MVC. From the diagram, the flows of the pointers are everywhere. It is not a good design. When there is a bug, you do not know where to start the debugging.

For more details on Model, View and Controller, you can read from wikipedia: MVC (Model View Controller).

Understand the 4 Layers of iOS

4 Layers of iOS - Core OS, Core Services, Media, Cocoa TouchAs per the course in Standford, Professor Paul divides the iOS into 4 different layers. Core OS layer is the closest to the hardware while Cocoa Touch Layer is the closet to the user Interface. In most simple iOS projects, we probably will spend 90% of the time on Cocoa Touch layer. But, if you are building some specific location based mobile apps, then you probably will spend more time on the Core service Layer.

The following are parts of the frameworks/features for each of the layers:-

Core OS
– Power Management
– Keychain Access
– File System
– OSX Kernel
– Sockets
– Security

Core Services
– Collections
– Address Book
– File Access
– SQLite
– Core Location
– Threading
– URl Utilities
– Networking

Media
– Core Audio
– Core Animation
– Audio Recording
– Quartz (2D)
– PDF
– JPEG, PNG, TIFF
– OpenGL ES

Cocoa Touch
– Multi-Touch (Gesture)
– View Hierarchy
– Localization
– Alerts
– Web View
– Map view
– Image Picker
– Camera
– Buttons

Most of above information and source of images are taken from Stanford University iPhone Application Development course.