Ios development-UI basics-Application Management (simple interface) Improvement 2, ios-ui

Source: Internet
Author: User

Ios development-UI basics-Application Management (simple interface) Improvement 2, ios-ui

This article uses dictionary-to-model to improve the code in the previous article.

Dictionary-to-model conversion, which has been introduced in previous articles, should be repeated here:

Dictionary-to-Model
Dictionary: used to store data. It is an nsdictionary to store data using key-value pairs)
Model: used to store data. A dictionary corresponds to a model. The model uses attributes to store data. It is a pure object.
@ Property (nonatomic, copy) NSString * name;
@ Property (nonatomic, copy) NSString * icon;

Dictionary-to-model conversion: a dictionary corresponds to a model. the attribute of the key-value pair is to assign the value of the key-value pair to the model attribute.
AppModel. name = dict [@ "name"];
AppModel. icon = dict [@ "icon"];

Attribute type and name: the type of the attribute and the key value of the key-value pair are the same. It is best to have the same name as the key value.

* Dictionary defects:
0> when writing code, the dictionary key does not have a smart prompt, but the model attribute can have a smart prompt.
1> the "key" is a string. If an error is written, the compiler does not report an error (no error during compilation). An error may occur during the runtime and it is difficult to find an error.

* Encapsulate the dictionary-to-model process into the "model"
* Cause: This "model" may be used in many places in the future (for example, many controllers use this model ), then, you need to write the code that assigns the data in the dictionary to the model attribute every time you use the model. If You encapsulate these value assignment statements into the model, this greatly simplifies the complexity of use and the amount of code.
  

 

* Implementation ideas:
1> receive an NSDictionary parameter in the model, and assign the value of the key value in NSDictioanry to the attribute of the model.
2> encapsulate an initWithDict method and an appWithDict method (specification)
-(Instancetype) initWithDict :( NSDictionary *) dict {}

+ (Instancetype) appModelWithDict :( NSDictionary *) dict {}

 

Application code structure and plist;

  

 

 

The source code is attached below:

KZAppModel. h

1 // 2 // KZAppModel. h 3 // UI basics-03-05-14 4 // 5 // Created by hukezhu on 15/5/15. 6 // 7 // 8 9 # import <Foundation/Foundation. h> 10 11 @ interface KZAppModel: NSObject12/** 13 * application icon 14 */15 @ property (nonatomic, copy) NSString * icon; 16/** 17 * Application name 18 */19 @ property (nonatomic, copy) NSString * name; 20 21/** 22 * initialize the object through the dictionary 23*24 * @ param dict dictionary object 25*26 * @ return the initialized model object 27 */28-(instancetype) initWithDict :( NSDictionary *) dict; 29 30 // class method 31 + (instancetype) appWithModelDict :( NSDictionary *) dict; 32 33 @ end

 

 

KZAppModel. m

1 // 2 // KZAppModel. m 3 // UI basics-03-05-14 4 // 5 // Created by hukezhu on 15/5/15. 6 // 7 // 8 9 # import "KZAppModel. h "10 11 @ implementation KZAppModel12 // object Method 13-(instancetype) initWithDict :( NSDictionary *) dict {14 15 // rewrite the default constructor code 16 if (self = [super init]) {17 18 // assign all attributes of the dictionary to model 19 self. icon = dict [@ "icon"]; 20 self. name = dict [@ "name"]; 21} 22 return self; 23} 24 // Class Method 25 + (instancetype) appWithModelDict :( NSDictionary *) dict {26 27 // note that self28 return [[self alloc] initWithDict: dict]; 29} 30 @ end

 

 

ViewController. m:

1 // 2 // ViewController. m 3 // 03-Application Management 4 // 5 // Created by hukezhu on 15/5/14. 6 // 7 // 8 9 # import "ViewController. h "10 # import" KZAppModel. h "11 12 @ interface ViewController () 13 @ property (nonatomic, strong) NSArray * apps; 14 @ end 15 16 @ implementation ViewController 17 18-(void) viewDidLoad {19 [super viewDidLoad]; 20 21 // number of applications in each row 22 int totalCol = 3; 23 24 25 // Add a small view 26 CGFloat appW = 80; 27 CGFloat appH = 100; 28 CGFloat Margat = 20; 29 CGFloat marginY = 20; 30 CGFloat hightMargin = 30; 31 CGFloat leftMargin = (self. view. frame. size. width-totalCol * appW-(totalCol-1) * margcol) * 0.5; 32 33 34 35 for (int I = 0; I <self. apps. count; I ++) {36 37 38 // calculate the row number and column number 39 int row = I/totalCol; 40 int col = I % totalCol; 41 42 CGFloat appX = leftMargin + (marg133 + appW) * col; 43 CGFloat appY = hightMargin + (marginY + appH) * row; 44 45 // 1. add view 46 47 // 1.1 create a UIView 48 UIView * appView = [[UIView alloc] init]; 49 // 1.2 set frame 50 appView. frame = CGRectMake (appX, appY, appW, appH); 51 // 1.3 sets the background color (which is easy for code verification and will be deleted later) 52 // appView. backgroundColor = [UIColor redColor]; 53 // 1.4 add this appView to view 54 [self. view addSubview: appView]; 55 56 // load data 57 // NSDictionary * dict = self. apps [I]; 58 // assign data to model object 59 KZAppModel * appModel = self. apps [I]; 60 61 // 2. add image UIImageView 62 CGFloat imageW = 60; 63 CGFloat imageH = 50; 64 CGFloat imageX = (appW-imageW) * 0.5; 65 CGFloat imageY = 0; 66 UIImageView * imageView = [[UIImageView alloc] init]; 67 imageView. frame = CGRectMake (imageX, imageY, imageW, imageH); 68 // imageView. backgroundColor = [UIColor blueColor]; 69 // imageView. image = [UIImage imageNamed: dict [@ "icon"]; 70 // retrieve data from model object 71 imageView. image = [UIImage imageNamed: appModel. icon]; 72 [appView addSubview: imageView]; 73 74 75 // 3. add the application name 76 77 CGFloat labelW = 80; 78 CGFloat labelH = 25; 79 CGFloat labelX = 0; 80 CGFloat labelY = imageH; 81 UILabel * label = [[UILabel alloc] init]; 82 label. frame = CGRectMake (labelX, labelY, labelW, labelH); 83 // label. backgroundColor = [UIColor grayColor]; 84 // label. text = dict [@ "name"]; 85 // retrieve the data name 86 label from the model object. text = appModel. name; 87 88 // set the font size 89 label. font = [UIFont systemFontOfSize: 13]; 90 // set the font to center 91 label. textAlignment = NSTextAlignmentCenter; 92 [appView addSubview: label]; 93 94 // 4. add the Download button 95 96 CGFloat downloadW = 60; 97 CGFloat downloadH = 25; 98 CGFloat downloadX = 10; 99 CGFloat downloadY = labelH + labelY; 100 UIButton * downloadBtn = [[UIButton alloc] init]; 101 downloadBtn. frame = CGRectMake (downloadX, downloadY, downloadW, downloadH), 102 // downloadBtn. backgroundColor = [UIColor yellowColor]; 103 // set the background image 104 [downloadBtn setBackgroundImage: [UIImage imageNamed: @ "buttongreen"] forState: UIControlStateNormal]; 105 [downloadBtn restart: [UIImage imageNamed: @ "buttongreen_highlighted"] forState: UIControlStateHighlighted]; 106 // method 1 for font setting 107 [downloadBtn setTitle: @ "Download" forState: UIControlStateNormal]; 108 109 // second method for font setting (not recommended) 110 downloadBtn. titleLabel. text = @ "Download"; 111 112 // set the font size to 113 downloadBtn. titleLabel. font = [UIFont systemFontOfSize: 15]; 114 [appView addSubview: downloadBtn]; 115 116 117 [downloadBtn addTarget: self action: @ selector (btnOnClick :) forControlEvents: UIControlEventTouchUpInside] 118} 119 120 121 122 123} 124/** 125 * Button clicking method 126*127 * @ param btn: Pass the button itself into the method, the method 129 */130-(void) btnOnClick :( UIButton *) btn {131 132 // NSLog (@ "------ % @", btn) is called when a button is clicked ); 133 btn. enabled = NO; 134 [btn setTitle: @ "downloaded" forState: UIControlStateNormal]; 135 136 CGFloat labelW = 120; 137 CGFloat labelH = 30; 138 CGFloat labelX = (self. view. frame. size. width-labelW) * 0.5; 139 CGFloat labelY = (self. view. frame. size. height-labelH) * 0.5; 140 UILabel * label = [[UILabel alloc] init]; 141 label. frame = CGRectMake (labelX, labelY, labelW, labelH); 142 label. text = @ "downloading"; 143 // set the font color to 144 label. textColor = [UIColor redColor]; 145 // set the font to center the 146 label. textAlignment = NSTextAlignmentCenter; 147 // set the background color 148 label. backgroundColor = [UIColor blackColor]; 149 150 // set the radius of the rounded corner to 151 label. layer. cornerRadius = 8; 152 // remove the excess part by 153 label. layer. masksToBounds = YES; 154 // set the transparency 155 label. alpha = 0.0; 156 // Add label to view 157 [self. view addSubview: label]; 158 // use block animation. The animation duration is 2 seconds. 159 [UIView animateWithDuration: 2.0 animations: ^ {160 label. alpha = 0.5; 161} completion: ^ (BOOL finished) {162 if (finished) {163 [UIView animateWithDuration: 2.0 delay: 0.1 options: UIViewAnimationOptionCurveLinear animations: ^ {164 label. alpha = 0.0; 165} completion: ^ (BOOL finished) {166 // The transparency is set to 0. This label is not displayed on the interface, but it is still in the memory, to save memory, you still need to delete 167 [label removeFromSuperview]; 168 169}]; 170} 171}] from the memory. 172 173} 174/** 175 * "lazy loading", load application data 176*177 */178-(NSArray *) apps {179 180 // If _ apps is empty, load data 181 if (_ apps = nil) {182 // obtain the full path of plist 183 NSString * path = [[NSBundle mainBundle] pathForResource: @ "app. plist "ofType: nil]; 184 185 // load the array 186 NSArray * dictArray = [NSArray arrayWithContentsOfFile: path]; 187 188 // create a variable array, to dynamically receive the model object 189 NSMutableArray * array = [NSMutableArray array]; 190 191 // retrieve the dictionary array through a loop, convert to model object 192 for (NSDictionary * dict in dictArray) {193 KZAppModel * appModel = [KZAppModel appWithModelDict: dict]; 194 [array addObject: appModel]; 195} 196 _ apps = array; 197} 198 return _ apps; 199} 200 201-(void) didReceiveMemoryWarning {202 [super didReceiveMemoryWarning]; 203 // Dispose of any resources that can be recreated.204} 205 206 @ end

 

Knowledge points added compared to the Code in the previous article:

1. dictionary-to-Model

The beginning of the article and the previous articles have been introduced many times. I will not repeat them here.

2. In the model class, when declaring and implementing the method, the returned value type is defined as instancetype, which is different from id:

1. The problem of using id as the return value of the method:

When receiving the return value of a method, you can use any type to receive it. compilation does not report errors, but errors may occur during running.

2. Notes for instancetype
1> instancetype indicates any object type, which is the same as id.
2> instancetype can only be used as the return value type, and variables and parameters cannot be declared like IDs.
3> when instancetype is used, the compiler checks the real types of instancetype. If the types do not match, a warning is issued during compilation. (Instancetype indicates the corresponding type in which it appears)

 

Here we still use the code to create the space. Apple provides xib to describe the local interface file (relative to the Global File described by storyboard ), using Xib, we can use the drag-and-drop method for visual development, which is more convenient. In the next article, we will use xib to improve this code.

 

 

 

 

 

 

  

Related Article

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.