iOS Development UI Chapter-MVC from the gradual optimization of code

Source: Internet
Author: User
Tags uikit

iOS Development UI Chapter-MVC from the gradual optimization of code

First, the requirements

Request to complete the following small application.

Two or one steps to optimize your code

Note: During the development process, the optimization process is step-by-step. (If a person to eat five steamed buns to eat full, then whether he ate the fifth directly, the front four without eating is full?) )

1. Code to complete the basic requirements (using the dictionary to model and Xib connection)

(1) File structure

(2) Main code

Dictionary to model section:

YYappInfo.h header File

1//2//  YYappInfo.h 3//  12-View Improvements (1) 4//5//  Created by Apple on 14-5-25.6//  Copyright (c) 2014 ITCA Se. All rights reserved. 7//8  9 #import <foundation/foundation.h>10 @interface yyappinfo:nsobject12 @property (nonatomic,copy) NSString *name;13 @property (nonatomic,copy) nsstring *icon;14 @property (nonatomic,strong,readonly) UIImage *img;15 16- (instancetype) Initwithdict: (nsdictionary *) dict;17/** Factory method */18 + (Instancetype) appinfowithdict: (NSDictionary *) dict ; @end

YYAPPINFO.M file

1//2//  YYAPPINFO.M 3//  12-View Improvements (1) 4//5//  Created by Apple on 14-5-25.6//  Copyright (c) 2014 ITCA Se. All rights reserved. 7//8  9 #import "YYappInfo.h" @interface Yyappinfo () {     UIImage *_img;13}14 @end15 @implementation Yyappinf O16-(Instancetype) Initwithdict: (Nsdictionary *) dict17 {     if (self=[super init]) {         self.name=dict[@ "name" ];20         self.icon=dict[@ "icon"];21     }22     return self;23}24 + (instancetype) Appinfowithdict: ( Nsdictionary *) Dict26 {     return [[Self alloc]initwithdict:dict];28}29-(UIImage *) img31 {_img=[     UIImage imagenamed:self.icon];33     return _img;34}35 @end

Xib section (YYappInfoView.h file):

Note: (The Xib view is associated with the Yyappinfoview and all three properties are wired)

1//2//  YYappInfoView.h 3//  12-View Improvements (1) 4//5//  Created by Apple on 14-5-25.6/  Copyright (c) 2014 Itcase. All rights reserved.  7//8  9 #import <uikit/uikit.h>10 @interface yyappinfoview:uiview12 @property (Strong, nonatomic) Iboutlet Uiimageview *appinfoviewimg;13 @property (Strong, nonatomic) Iboutlet UILabel *appinfoviewlab;15 @property (Strong, no natomic) Iboutlet UIButton *appinfoviewbtn;16 @end

Main Feature Implementation section:

YYVIEWCONTROLLER.M file

 1//2//YYVIEWCONTROLLER.M 3//12-View improvements (1) 4//5//Created by Apple on 14-5-25. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYappInfo.h" #import "YYappInfoView.h" @interface Yyviewcontrolle R () @property (nonatomic,strong) nsarray *apps;15 @end16 17//Development ideas 18//1. Load plist file (dictionary to model provides interface) 19//2. Use the Xib file to complete a single view20//3. Calculates the coordinates, using the for loop to display the view to the interface 21//4. Optimization code @implementation YYViewController23 method, lazy loading 25-( Nsarray *) Apps26 {if (!_apps) {NSString *path = [[NSBundle mainbundle]pathforresource:@ ' app.plist ' Oftyp e:nil];29 Nsarray * Arraym = [Nsarray arraywithcontentsoffile:path];30 nsmutablearray *appinfoa Rray=[nsmutablearray array];32 for (nsdictionary *dict in Arraym) {[Appinfoarray Addobject:[yyappin Fo appinfowithdict:dict]];34}35 _apps = appinfoarray;36}37 return _apps;38}39-(void) Viewdi dLoad41 {[Super Viewdidload];43 NSLog (@ "%d", self.apps.count), int totalloc = 3;46 cgfloat appvieww = 80;47 cgfloat appview H = 90;48 cgfloat margin = (self.view.frame.size.width-totalloc*appvieww)/(totalloc+1);         ps.count;51 for (int i = 0; i < count; i++) {int row = i/totalloc;53 int loc = i%totalloc;54 CGFloat appviewx = margin + (margin + appvieww) * loc;56 cgfloat appviewy = margin + (margin + AP) PVIEWH) * row;57 yyappinfo *appinfo=self.apps[i];59 60//Take out data in Xib for Nsarray *arrym=[[nsbundle mainbundle]loadnibnamed:@ "Appinfoxib" Owner:nil options:nil];62 YYappInfoView *appinfoview=[arry         M firstobject];63//Set Location: Appinfoview.frame=cgrectmake (appviewx, Appviewy, APPVIEWW, APPVIEWH); 65         Set Value appinfoview.appinfoviewimg.image=appinfo.img;67 appinfoview.appinfoviewlab.text=appinfo.name;68        Add to view 69 appinfoview.appinfoviewbtn.tag=i;70 [appinfoview.appinfoviewbtn addtarget:self Action: @selector (Click:) ForContro levents:uicontroleventtouchupinside];71 [Self.view addsubview:appinfoview];72}73}74-(void) Click: (UIButton * ) btn75 {btn.enabled=no;77 yyappinfo *appinfo=self.apps[btn.tag];78 UILabel *lab=[[uilabel Alloc]initwithfra Me:cgrectmake (max.,];79) [Lab setbackgroundcolor:[uicolor lightgraycolor]];80 [Lab Settextalignment:nst extalignmentcenter];81 [Lab settext:[nsstring stringwithformat:@ "%@ successful Download", appinfo.name]];82 [Self.view addSubview:l ab];83 lab.alpha=1.0;85 [UIView animatewithduration:2.0 animations:^{86 lab.alpha=0;87}complet ion:^ (BOOL finished) {removefromsuperview];89 [lab}];90}91 @end

2. Optimize for 1 (encapsulate the data presentation part into the view)

Description: Search on the basis of 1 and there will be parts that can be optimized

1) Ideas for improvement:

(1) The 66~67 of the main file in 1 can the settings of the control properties be taken in the view?

(2) 1 The 61~62 line is the operation that reads information from the Xib file, and there is not much association with the host controller, can it also be encapsulated in the view?

(3) When the above two steps completed, the main file 69 line after the button action and button click event is very abrupt, placed in the host controller is no longer appropriate, can be put in the view to be processed

2) Follow the above ideas to optimize the code as follows:

An optimized view that provides an interface to the outside of the view section to encapsulate data processing in-house

YYappInfoView.h File Code:

1//2//  YYappInfoView.h 3//  12-View Improvements (1) 4//5//  Created by Apple on 14-5-25.6/  Copyright (c) 2014 Itcase. All rights reserved. 7//8  9 #import <uikit/uikit.h>10 @class yyappinfo;11 @interface yyappinfoview:uiview12 13//Read//+ (instanc ETYPE) appinfoview;15//Open only one Data interface (Instancetype) Appinfoviewwithappinfo: (Yyappinfo *) appinfo;17 @end

YYAPPINFOVIEW.M File Code

Note: The properties in the file and the click are all connected.

 1//2//YYAPPINFOVIEW.M 3//12-View improvements (1) 4//5//Created by Apple on 14-5-25. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYappInfoView.h" #import "YYappInfo.h" 11//private extension, bring the attributes in @interface Yyappinfoview () @property (str Ong, nonatomic) iboutlet Uiimageview *appinfoviewimg;14 @property (Strong, nonatomic) Iboutlet UILabel *appinfoviewlab; @property (Strong, nonatomic) Iboutlet UIButton *appinfoviewbtn;16 @property (strong,nonatomic) Yyappinfo *appinfo;17 @end19 @implementation YYappInfoView20 + (instancetype) appInfoView22 {nsarray *arrym=[[nsbundle Mainbundle]loa dnibnamed:@ "Appinfoxib" Owner:nil options:nil];24 yyappinfoview *appinfoview=[arrym firstObject];25 return appinfo View;26}27 + (instancetype) Appinfoviewwithappinfo: (Yyappinfo *) appinfo29 {Yyappinfoview *appinfoview=[self appIn foview];31 appinfoview.appinfo=appinfo;32 return appinfoview;33}34-(void) Setappinfo: (Yyappinfo *) appinfoc36 { 37//Here AMust record the change of _appinfo=appinfoc;39 self.appinfoviewimg.image=appinfoc.img; 
Self.appinfoviewlab.text=appinfoc.name;
41}
-(Ibaction) Click {     self.appinfoviewbtn.enabled=no;45     //yyappinfo *appinfo=self.apps[];46     yyappinfo *appinfo=self.appinfo;48     UILabel *lab=[[uilabel alloc]initwithframe:cgrectmake (60, 450, 200, 20 )];49     [Lab setbackgroundcolor:[uicolor lightgraycolor]];50     [Lab Settextalignment:nstextalignmentcenter];     [Lab settext:[nsstring stringwithformat:@ "%@ successfully downloaded", appinfo.name]];52     //Add Lab to Parent view (i.e. view)     [ Self.superview addsubview:lab];54     lab.alpha=1.0;56     [UIView animatewithduration:2.0 animations:^ {         lab.alpha=0;58     }completion:^ (BOOL finished) {         [lab removefromsuperview];60     }];61}62 63 64 @end

Optimized Master Controller Section

YYVIEWCONTROLLER.M File Code

 1//2//YYVIEWCONTROLLER.M 3//12-View improvements (1) 4//5//Created by Apple on 14-5-25. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYappInfo.h" #import "YYappInfoView.h" @interface Yyviewcontrolle     R () @property (nonatomic,strong) nsarray *apps;15 @end16 @implementation YYViewController17-(Nsarray *) apps19 {20 if (!_apps) {NSString *path = [[NSBundle mainbundle]pathforresource:@ ' app.plist ' oftype:nil];22 NSArra Y * Arraym = [Nsarray arraywithcontentsoffile:path];23 nsmutablearray *appinfoarray=[nsmutablearray arr Ay];25 for (nsdictionary *dict in Arraym) {[Appinfoarray addobject:[yyappinfo appinfowithdict:dict] ];27}28 _apps = appinfoarray;29}30 return _apps;31}32-(void) viewDidLoad34 {[Super V]  iewdidload];36 NSLog (@ "%d", self.apps.count), PNs int totalloc = 3;39 cgfloat appvieww = 80;40 cgfloat ApPVIEWH = 90;41 cgfloat margin = (self.view.frame.size.width-totalloc*appvieww)/(totalloc+1); int Count=se lf.apps.count;44 for (int i = 0; i < count; i++) {$ int row = i/totalloc;46 int loc = I%totalloc;4  7 CGFloat appviewx = margin + (margin + appvieww) * loc;49 cgfloat appviewy = margin + (margin + APPVIEWH) * ROW;50 51/* Ideas: 52 To achieve the effect appinfoview.appinfo=appinfo;53 optimized becomes Appinfovie         W.appinfo=self.apps[i];54 to do the above code, you need to add a new appinfo class in the view of the properties, so that the data--"view of the conversion can not be done in the master controller, the program structure at a Glance 55 */56 Yyappinfo *appinfo=self.apps[i];57 Yyappinfoview *appinfoview=[yyappinfoview appinfoviewwithappinfo:appinfo         ];58//Set location Appinfoview.frame=cgrectmake (appviewx, Appviewy, APPVIEWW, APPVIEWH); 60//Add 61 [Self.view addsubview:appinfoview];62}63}64 @end

3. Further optimization of 2 (take the data processing part to the model)

(1) Thinking: The Dictionary to the model part of the data processing operations, get the model to deal with, so that the outside world does not need to care about the internal details of data processing.

(2) The optimized code is as follows

An interface is opened outward in the YYappInfo.h file, returning a well-handled array.

1//2//  YYappInfo.h 3//  12-View Improvements (1) 4//5//  Created by Apple on 14-5-25.6//  Copyright (c) 2014 ITCA Se. All rights reserved. 7//8  9 #import <foundation/foundation.h>10 @interface yyappinfo:nsobject12 @property (nonatomic,copy) NSString *name;13 @property (nonatomic,copy) nsstring *icon;14 @property (nonatomic,strong) UIImage *img;15 16-( Instancetype) Initwithdict: (nsdictionary *) dict;17/** Factory method */18 + (Instancetype) appinfowithdict: (NSDictionary *) dict; + (Nsarray *) appinfoarray;20 @end

Data processing in the YYAPPINFO.M file

 1//2//YYAPPINFO.M 3//12-View improvements (1) 4//5//Created by Apple on 14-5-25. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYappInfo.h" @interface yyappinfo () @end12 @implementation YYappInfo13-(instancetype) Initwithdict: (Nsdictionary *) dict14 {if (self=[super init]) {self.name=dict[@ "name"];17 self.icon=dict[@ "icon "];18}19 return self;20}21 + (instancetype) appinfowithdict: (Nsdictionary *) dict23 {[[Self alloc] Initwithdict:dict];25}26-(UIImage *) img28 {_img=[uiimage imagenamed:self.icon];30 return _img;31}32 33// Take the data Processing section to the model to handle the Nsarray * appinfoarray35 {nsstring *path = [[NSBundle mainbundle]pathforresource:@ "App.plist" O ftype:nil];37 Nsarray * Arraym = [Nsarray arraywithcontentsoffile:path];38, Nsmutablearray *appinfoarray=[NS Mutablearray array];40 for (nsdictionary *dict in Arraym) {[Appinfoarray addobject:[yyappinfo appInfoWithDi Ct:dict]];}43 return appinfoarray;44}45 @end 

No longer need to care about the internal details of data processing in the host controller

The yyviewcontroller.m file is now only responsible for the coordination between the model and the view. That's almost it.

 1//2//YYVIEWCONTROLLER.M 3//12-View improvements (1) 4//5//Created by Apple on 14-5-25. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYappInfo.h" #import "YYappInfoView.h" @interface Yyviewcontrolle     R () @property (nonatomic,strong) nsarray *apps;15 @end16 @implementation YYViewController17-(Nsarray *) apps19 {20     if (!_apps) {_apps=[yyappinfo appinfoarray];22}23 return _apps;24}25-(void) ViewDidLoad27 {28 [Super viewdidload];29 int totalloc = 3;31 cgfloat appvieww = 80;32 cgfloat appviewh = 90;33 CGFL Oat margin = (SELF.VIEW.FRAME.SIZE.WIDTH-TOTALLOC*APPVIEWW)/(totalloc+1); int count=self.apps.count;36 fo          R (int i = 0; i < count; i++) {PNs int row = i/totalloc;39 int loc = I%TOTALLOC;40 41  CGFloat appviewx = margin + (margin + appvieww) * loc;42 cgfloat appviewy = margin + (margin + appviewh) *row;43 yyappinfo *appinfo=self.apps[i];45 Yyappinfoview *appinfoview=[yyappinfoview Appinfoview  Withappinfo:appinfo];46 Appinfoview.frame=cgrectmake (appviewx, Appviewy, APPVIEWW, AppviewH); [Self.view addsubview:appinfoview];48}49}50 @end

Implementation results:

4. Additional Information

View Packaging Ideas

(1) If a view inside the child control is more, it is generally considered to customize a view, the creation of its internal sub-controls to screen up, do not let outside concern

(2) The outside world can pass the corresponding model data to the View,view to get the model data and set the corresponding data for the inner child control.

Three, the MVC mechanism simple explanation

Description

(1) In the development process, as the controller to deal with the magnitude should be very light, should not worry about not worry. Good coordination of models and views is OK, learn to be a good boss.

(2) Three parts of the work, the data model is only responsible for data processing, the view part is responsible for the data to be displayed, two parts are passive, waiting for the large Butler controller field.

(3) in OC, if there is a channel between the view and the data model, is the controller in a runaway state?

iOS Development UI Chapter-MVC from the gradual optimization of code

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.