Wednesday, February 21, 2018

iOS - Fix Massive View Controller using MVP+VM Architecture

To solve the Massive View Controller, we distribute the tasks to different classes:

1. Router


  • The Router class will capable to handle all navigations such as segue or custom.
  • Capable to construct the view controller
  • Capable to pass data to other view controllers

A sample Router class is shown below:


So we will always call addContracts() function when ever construct a view controller

func showLoginByRemove(_ viewController: UIViewController?) {
        let loginController = LoginViewController.getController()
        LoginRouter.addContracts(loginController, parent: self, profile: MyProfile())
        transition(fromVC: viewController, animationDuration: 0.5, toVC: loginController)
}

2. SBControl
    This class will keep all storyboard controls, and its makeups such as setting font, colours and localised texts and animations etc..

I am not repeating how to do this, Its well explained here see the section "Solution 2: Presentation Controls"

So
The VC (View Controller) can have minimum one IBOutlet reference to the Object control.

3. Presenter  - implements UIEvents protocol
    Responsible to handle user actions from View Controller. This is just a dispatcher. Handle a little business logics. Presenter will ask to viewmodel to perform the data manipulations and will return the result to the view controller using the DisplayUI protocol which is implemented by View Controller.
    Presenter will give the navigation task to the router
    Presenter will give the display task to the view controller
    Presenter will give the network operations to the service class

4. Service - optional
     Responsible to all network operations. Presenter will hold a protocol reference which is implemented by Service class

5. ViewModel
     There will be separate view models for each view. It will be responsible to handle business logic as well as the presentation logic. Both will be grouped using protocols.

6. ViewController
    Responsible to the VC life cycle. Inform all UI actions to the Presenter. ViewController implements a DisplayUI protocol.

7. UIController (optional)
    Handle the tableview/collection/text view delegates here to reduce the code in View Controller and also to distribute the functionalities.




Following is the template to create the files.

https://github.com/davidpaul0880/Swift-Template

Can post more when get more free time..

But post comment if you have any questions, or need clarifications.