Swift Tutorial 17-fade MVC and use the MVVM framework to develop a lightweight and maintainable Ios/android app

Source: Internet
Author: User
Tags constant definition

MVVM is a mobile development framework designed by Microsoft to address the bloated problem of traditional MVC framework controllers for traditional MVC frameworks.

M:

Model models, which are data models; for example, a micro-blog, corresponding to all the fields to synthesize a microblog overall, this whole is model


V:

View view, which is used only to display views such as iOS Uiview,cell; of course, in iOS storyboard, view is always associated with the controller, which is not a strict view

If we define a view with pure handwritten code, then it's a very strict view.


Vm:

The ViewModel view model, which binds a view and model, acts as a bridge.

For example, a Weibo cell, the corresponding data is bound to a model, the obtained data is bound to the model of the various properties.


The traditional C in MVC represents the controller, which is responsible for the logical processing and data binding, updating the view, the code is too complex, the maintenance will be difficult;

The MVVM framework is to lighten the controller controllers;

The network request, data binding, update view, are stripped out;

It's just a simple jump and a partial proxy in the controller.


Comparing with the MVVM development Framework is the controller using TableView; Cell customization; define the desired model; define the corresponding interface for the ViewModel call


Here's an MVVM framework development, demo with network request



Catalogue Description:

Resourse: Storing pictures, audio video files, IB files

Controllers: Storing the View controller

Vender: Open source Framework, or components of your own package

Utiltools: Common code for encapsulation, constant definition, configuration file, etc.

ViewModel: Get different data based on different view and bind to model

View: Custom views such as cell or pure handwritten view

Model: Data models, which is the whole of all the fields required for view


Implementation results:

A tableview shows several dynamic including, picture, text;



Technical points:

MVVM Framework

Afnetworking Network Requests

Mbprogresshud wait for prompt

Custom cell

Block closure pass value, package code


Implementation process:

1. Introduction of OC-related frameworks


Create a new OC file in the SWIFT project and ask if you want to create a new bridge to the OC file, select Yes, generate a Header.h file, and import the corresponding OC header file to use

, there is a swiftdemo-bridging-header.h file in the project

Import frames such as AF

Swiftdemo-bridging-header.h

Use  the This file to import your target's public headers so would like to expose to swift.//#import "Afnetworki Ng.h "#import" MBProgressHUD.h "#import" Uiimageview+afnetworking.h "

2. Use storyboard to create a custom cell bound to the cell class with an identifier of Testcell




Testcell.swift Class of bindings

  testcell.swift//  swiftdemousingaf////  Created by Mbinyang on 15/4/8.//  Copyright (c) 2015 Cc.huanyouwang. All rights reserved.//import Uikitclass testcell:uitableviewcell{    @IBOutlet var imageView2: uiimageview!    @IBOutlet var textlabel2:uilabel!    @IBOutlet var location:uilabel!    Override Func awakefromnib ()    {        super.awakefromnib ()           }    override Func setselected (Selected:bool, Animated:bool)    {        super.setselected (selected, animated:animated)           }       /**    * Configure the contents method of the cell  *    /func Configcellwithstatusmodel (model:statusmodel!)    {        Self.imageView2.setImageWithURL (Nsurl (String:model.imageURL), Placeholderimage:uiimage (named: " PlaceHolder "))        Self.textLabel2.text = model.text        self.location.text = Model.location    }}


The cell contains a imageview and two labels


3. Definition of constants, macro definitions similar to OC


Stringconstant.swift

Constants start with lowercase k, rest uppercase, and can be underlined

Constants for Swift, using let to define constants;

  stringconstant.swift//  swiftdemo////  Created by Mbinyang on 15/4/8.//  Copyright (c) 2015 Cc.huanyouwang. All rights reserved.//import foundationimport Uikitlet kgetstatusurl = "http://lovemyqq.sinaapp.com/ getstate.php ' Let Kaccesstoken = ' 2.00hze3af0gvjsm551ca8e0920nf13n ' let Kuid = ' 5117873025 ' let Kaccesstokenkey = ' Access_ Token ' Let Kuidkey = ' uid ' let kparamdic = [Kaccesstokenkey:kaccesstoken,kuidkey:kuid]let Kredcolor = Uicolor.redcolorle T kimagekey = ' image ' let Kdatekey = ' Date ' let Klocationkey = ' address ' let Kcontentkey = ' content ' let Kresultkey = ' result ' Let Kstatekey = ' state '//other complex type, can use function definition//func RGBA (r:cgfloat, G:cgfloat, B:cgfloat, a:cgfloat)//{//    return Uicolor (red:r/255.0, green:g/255.0, blue:b/255.0, alpha:a)//}//use the following methods//var Thecolor:uicolor = RGBA (255, 255, 0, 1)


4. Package af is a common method for easy ViewModel invocation


Afrequest.swift

afrequest.swift//swiftdemo////Created by Mbinyang on 15/4/8.//Copyright (c) 2015 Cc.huanyouwang. All rights reserved.//import uikitpublic Typealias successblock = (obj:anyobject)->void!class afrequest:nsobject{V    Ar mainurl:string!    var paramdict:[string:string]!    var successblock:successblock!       var manager:afhttprequestoperationmanager var hud:mbprogresshud! Init (mainurl:string,paramdict:[string:string],successblock:successblock) {Self.mainurl = MainURL SELF.PA Ramdict = paramdict Self.successblock = Successblock Self.manager = Afhttprequestoperationmanager () s    Uper.init ()} func Startrequestwithhudonview (view:uiview!)  {Self.hud = Mbprogresshud.showhudaddedto (view, animated:true) Self.hud.labelText = "Requesting ..." var op = Self.manager.GET (Self.mainurl, Parameters:self.paramDict, success: {(operation:afhttprequest operation!, Responseobject:anyobject!) in Var arr:anyobject! = Nsjsonserialization.jsonobjectwithdata (Responseobject as NSData, Options:NSJSONReadingOptions.AllowFragments,                Error:nil) println (arr!)               unowned var unself:afrequest = self Unself.successblock (obj:arr!)               UnSelf.hud.customView = Nil UnSelf.hud.labelText = "loaded successfully!"                UnSelf.hud.hide (False, Afterdelay:3)}, Failure: {(operation:afhttprequestoperation!, error:nserror!)                In println ("Request error:" + error.localizeddescription) unowned var unself:afrequest = self UnSelf.hud.hide (True)}) Op.responseserializer = Afhttpresponseserializer () op. Start ()}}


5. Encapsulate a model class according to the data required by the View/cell.


such as encapsulating a model class of Statusmodel state models corresponding to the cell data field

Statusmodel.swift

Contains, attributes, and accessors

  statusmodel.swift//  swiftdemousingaf////  Created by Mbinyang on 15/4/8.//  Copyright (c) 2015 Cc.huanyouwang. All rights reserved.//import Uikitclass statusmodel:nsobject{        var imageurl:string!    var text:string!    var location:string!              Override  Init ()    {        //todo    }                init (imageurl:string!,text:string,location:string)    {        Self.imageurl = ImageURL        self.text = text        self.location = location    }        var Configmodel: ( string!,string!,string!)    {        set        {            Self.imageurl = newvalue.0            self.text = newvalue.1            self.location = newvalue.2        }        Get        {            return (self.imageurl,self.text,self.location)        }    }        //Omit set shorthand get    var urlofimg:string    {        return Self.imageurl    }   }


6.ViewModel calls the corresponding interface according to the data required by the view, and binds the data to the model


Parse JSON data, bind to model

Statusviewmodel.swift

statusviewmodel.swift//swiftdemo////Created by Mbinyang on 15/4/8.//Copyright (c) 2015 Cc.huanyouwang. All rights Reserved.//import Uikitpublic class statusviewmodel:nsobject{func requeststatuslist (view:UIView!,blk:Succ                                    Essblock) {var af = afrequest (Mainurl:kgetstatusurl, paramdict:kparamdic) {(obj), void! in var dico = obj as dictionary<string,anyobject> var arr1:anyobject?             = Dico[kresultkey] var arrreal = arr1 as array<dictionary<string,dictionary<string,string>>> var Modelarray = array<statusmodel> ()/** parse the resulting JSON data into the model array */For Di  CT in arrreal {var dic = dict[kstatekey]! as dictionary<string,string> var                Smodel = Statusmodel () Smodel.imageurl = dic[kimagekey]!                Smodel.text = dic[kcontentkey]! Smodel.location = dic[klocationkey]!                        Modelarray.append (Smodel)} println (Modelarray[0]) blk (Obj:modelarray) Return Void ()} af.startrequestwithhudonview (view)}}


Call ViewModel display data in 7.TableViewController controller


tableviewcontroller.swift//swiftdemo////Created by Mbinyang on 15/4/8.//Copyright (c) 2015 Cc.huanyouwang. All rights Reserved.//import Uikitclass tableviewcontroller:uitableviewcontroller{var modelArray = Array<StatusMod El> () override Func Viewdidload () {super.viewdidload () LoadData ()} ove Rride func didreceivememorywarning () {super.didreceivememorywarning ()} override Func Numberofsec  Tionsintableview (Tableview:uitableview), Int {return 1} override func TableView (TableView: UITableView, Numberofrowsinsection section:int), Int {return modelarray.count} override Func TableView (Tableview:uitableview, Cellforrowatindexpath indexpath:nsindexpath), UITableViewCell {VA R Smodel = Self.modelarray[indexpath.row] var cell = tableview.dequeuereusablecellwithidentifier ("TestCell", forInd Expath:indexpath) as TestCell Cell.configcellwithstatusmodel (Smodel as Statusmodel) return cell}/** * Request * Back when loading data for the first time            Back to NULL */func LoadData () {Statusviewmodel (). Requeststatuslist (Self.view, Blk: {(obj), void! in unowned var weak_self:tableviewcontroller = self println ("This is the first time the data is loaded block\ (__function__)") WEA        K_self.modelarray = obj as array<statusmodel> weak_self.tableView.reloadData () return Void () })    }}

Call ViewModel and then Reloaddata ()


Of course, ViewModel may also be called on the view, such as a button on the cell, the click of the button will make the network request, also need to call ViewModel


8. Summary


We can see that in Tableviewcontroller, the code is very small. The original corresponding network request, for the view update is placed in the controller;

Using MVVM can greatly reduce the controller's code, which is less coupled and easier to maintain.



9. Other, there is an event trigger on the view


If the cell or view has a click event, or other event, you can use a closure package, similar to the AF request above.



Swift Series Tutorial:http://blog.csdn.net/yangbingbinga/article/category/3050845









Swift Tutorial 17-fade MVC and use the MVVM framework to develop a lightweight and maintainable Ios/android app

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.