iOS Development UI article-implement a simple microblogging interface layout with pure code custom UITableViewCell

Source: Internet
Author: User
Tags ranges

First, the realization effect

Ii. steps to customize a TableView using pure code

1. Create a new class that inherits from UITableViewCell

2. Overriding Initwithstyle:reuseidentifier: Methods

Add all the child controls that need to be displayed (you don't need to set the child control's data and frame, and the child controls are added to the Contentview)

Make child controls one-time property settings (some properties only need to be set once, such as fonts \ fixed pictures)

3.2 Models available

Data model: Storing text data \ Picture data

Frame model: The height of the Frame\cell that holds the data model \ All child controls

4.cell has a frame model (don't have a data model directly)

5. Override the setter method of the Frame model property: Set the child control's display data and frame in this method

The initialization of the 6.FRAME model data has been done in a lazy manner (each cell corresponds to the frame model data is loaded only once)

III. file structure and implementation code

1. File structure

2. Implementation code:

NJWeibo.h file

1 #import <Foundation/Foundation.h> 2  @interface njweibo:nsobject 4 @property (nonatomic, copy) NSSt Ring *text; Content 5 @property (nonatomic, copy) NSString *icon; Avatar 6 @property (nonatomic, copy) NSString *name; Nickname 7 @property (nonatomic, copy) NSString *picture; With Figure 8 @property (nonatomic, assign) BOOL VIP; 9-(ID) initwithdict: (Nsdictionary *) DICT;11 + (ID) weibowithdict: (nsdictionary *) dict;12 @end

NJWEIBO.M file

1 #import "NJWeibo.h" 2  3 @implementation Njweibo 4  5-(ID) initwithdict: (Nsdictionary *) dict 6 {7     if (self = [Super Init]) {8         [Self setvaluesforkeyswithdictionary:dict]; 9     }10     return self;11}12 + (ID) weibowithdict: (Nsdictionary *) dict14 {     return [[Self alloc] Initwithdict :d ict];16}17 @end

NJWeiboCell.h file

1 #import <UIKit/UIKit.h> 2 @class njweiboframe; 3  4 @interface Njweibocell:uitableviewcell 5/** 6  *  receive external incoming Model 7  */8//@property (nonatomic, S Trong) Njweibo *weibo; 9 @property (nonatomic, strong) Njweiboframe *weiboframe; receives the outside frame model, because the frame model includes the data text model, and the frame data. one + (instancetype) Cellwithtableview: (UITableView *) tableview;13 @end

NJWEIBOCELL.M file

  1 #import "NJWeiboCell.h" 2 #import "NJWeibo.h" 3 #import "NJWeiboFrame.h" 4 5 #define Njnamefont [Uifont Systemfon  TOFSIZE:15] 6 #define Njtextfont [Uifont systemfontofsize:16] 7 8 @interface Njweibocell () 9/** 10 * Avatar 11 */12 @property (nonatomic, weak) Uiimageview *iconview; /** * VIP * * @property (nonatomic, weak) Uiimageview *vipview; 17/** 18 * with picture */@property (nonatomic, weak) Uiimageview *pictureview; 21/** 22 * Nickname * * * @property (nonatomic, weak) UILabel *namelabel; 25/** 26 * Text * * @property (nonatomic, weak) UILabel *introlabel; @end @implementation Njweibocell + (instancetype) Cellwithtableview: (UITableView *) TableView 34 {35/ /NSLog (@ "Cellforrowatindexpath"); The static NSString *identifier = @ "status"; 37//1. Cache Njweibocell *cell = [TableView dequeuereusablecellwithidentifier:identifier]; 39//2. Create the "if" (cell = = nil) {The cell = [[Njweibocell alloc]initwithStyle:uitableviewcellstyledefault Reuseidentifier:identifier]; (a) the return cell; 44} 45 46 47/** 48 * Construction method (called when initializing an object) 49 * Generally add the child controls that need to be displayed in this method./-(ID) Initwithstyle: (uitableviewcellstyl e) style Reuseidentifier: (NSString *) reuseidentifier (*) (*) = [Super Initwithstyle:style Reuseidentifier:reuseide Ntifier]; if (self) {55//Let custom cell and system cell, as soon as it is created, has some child controls available to us using 56//1. Create Avatar Uiimageview *ico NView = [[Uiimageview alloc] init]; [Self.contentview Addsubview:iconview]; Self.iconview = IconView; 60 61//2. Create nickname UILabel *namelabel = [[UILabel alloc] init]; Namelabel.font = Njnamefont; +//Namelabel.backgroundcolor = [Uicolor Redcolor]; [Self.contentview Addsubview:namelabel]; Self.namelabel = Namelabel; 67 68//3. Create VIP Uiimageview *vipview = [[Uiimageview alloc] init]; Vipview.image = [UIImage imagenamed:@ "VIP"]; [Self.contentview Addsubview:vipview]; Self.vipview = Vipview; 73 74//4. Create body UILabel *introlabel = [[UILabel alloc] init]; Introlabel.font = Njtextfont; Introlabel.numberoflines = 0; //Introlabel.backgroundcolor = [Uicolor Greencolor]; [Self.contentview Addsubview:introlabel]; Self.introlabel = Introlabel; 81 82//5. Create map with Uiimageview *pictureview = [[Uiimageview alloc] init]; [Self.contentview Addsubview:pictureview]; Self.pictureview = Pictureview; The other is the return self; 89} 90 91 92-(void) Setweiboframe: (Njweiboframe *) Weiboframe//weiboframe Set Method94 _weiboframe = Weiboframe; 95 96//1. Assigning data to child controls [self settingdata]; 98//2. Set Frame 99 [ Self settingframe];100}101 102 103/**104 * Set data for child controls */106-(void) settingData107 {108Njweibo *weibo = Self.weiboFrame.weibo;
The Weibo property (also the class object) that is equivalent to removing the Weiboframe property of the Cell object (which is the class object) to the object variable Weibo will invoke the set method of the Weibo property in Weibofrema to set the frame's data109 110//Set avatar 111 self.iconView.image = [UIImage imagenamed:weibo.icon];112//Set nickname 113 Self.namelabel . Text = weibo.name;114//Set vip115 if (WEIBO.VIP) {Self.vipView.hidden = no;117 Self.namelabel . TextColor = [Uicolor redcolor];118}else119 {self.vipView.hidden = yes;121 Self.nameLabel.tex TColor = [Uicolor blackcolor];122}123//set content 124 Self.introLabel.text = weibo.text;125 126//set with Figure 127 if (weibo.picture) {//has a map of self.pictureView.image = [UIImage imagenamed:weibo.picture];129 self.pi Ctureview.hidden = no;130}else131 {self.pictureView.hidden = yes;133}134}135/**136 * Set the child control's F rame137 */138-(void) settingFrame139 {140 141//set Avatar's frame142 self.iconView.frame = self.weiboframe.iconf;14 3 144//Set nickname frame145 Self.nameLabel.frame = self.weiboframe.namef;146 147//Set VIP frame148 Self.vipView.frame =self.weiboframe.vipf;149 150//Set body frame151 self.introLabel.frame = self.weiboframe.introf;152 153 Set the frame154 155 if (self.weiboFrame.weibo.picture) {//have a map 156 self.pictureView.frame = Self.weiboframe. pictruef;157}158}159 160/**161 * Calculate the width of the text 162 *163 * @param str need to calculate the text 164 * @param font Text display fonts 165 * @param maxSize Text Display range 166 *167 * @return text occupies a true width 168 */169-(cgsize) sizewithstring: (NSString *) str font: (Uifont *) F Ont maxSize: (cgsize) maxSize170 {171 Nsdictionary *dict = @{nsfontattributename:font};172//If future computed text ranges beyond the specified range , returns the specified range 173//If the range of text to be computed in the future is less than the specified range, the true range is returned 174 cgsize size = [str boundingrectwithsize:maxsize options:nsst Ringdrawinguseslinefragmentorigin attributes:dict context:nil].size;175 return size;176}177 178 @end

NJWeiboFrame.h file

1//  frame to hold each row of data, calculate frame 2  3 #import <Foundation/Foundation.h> 4 @class Njweibo; 5 @interface Njweib Oframe:nsobject 6/** 7  *  Avatar Frame 8 *  /9 @property (nonatomic, assign) cgrect iconf;10/**11  *  nickname F Rame12  */13 @property (nonatomic, assign) cgrect namef;14/**15  *  vip frame16  */17 @property ( Nonatomic, assign) cgrect vipf;18/**19  *  text frame20 */21  @property (nonatomic, assign) CGRect introf;22 /**23  *  map of Frame24  */25 @property (nonatomic, assign) cgrect pictruef;26/**27  *  Row height  */29 @property (nonatomic, assign) cgfloat cellheight;30-/**32  *  model data  @property (nonatomic, Strong) Njweibo *weibo; @end

NJWEIBOFRAME.M file

 1 #import "NJWeiboFrame.h" 2 #import "NJWeibo.h" 3 #define Njnamefont [Uifont systemfontofsize:15] 4 #define NJTEXTFONT [ Uifont Systemfontofsize:16] 5 6 7 @implementation Njweiboframe 8 9 ten-(void) Setweibo: (Njweibo *) weibo11 {_weib     o = weibo;13 14//gap cgfloat padding = 10;16 17//Set avatar Frame18 cgfloat iconviewx = padding;19 CGFloat iconviewy = padding;20 cgfloat iconvieww = 30;21 cgfloat iconviewh = 30;22 self.iconf = CGRectMake (Iconviewx, Iconviewy, ICONVIEWW, ICONVIEWH); 23 24//Set nickname for Frame25//nickname x = Avatar Max X + gap-CGFloat Namelab ElX = Cgrectgetmaxx (self.iconf) + padding;27//Calculate the width of the text cgsize namesize = [Self sizewithstring:_weibo.name font: Njnamefont Maxsize:cgsizemake (maxfloat, maxfloat)];29-CGFloat namelabelh = namesize.height;31 CGFloat NameL ABELW = namesize.width;32 CGFloat namelabely = Iconviewy + (ICONVIEWH-NAMELABELH) * 0.5;33 SELF.NAMEF = CGRectMak E (Namelabelx, namelabely, NAMELABELW, NAMELABELH); 34 35//Set VIP frame36 cgfloat vipviewx = Cgrectgetmaxx (SELF.NAMEF) + padding;37 CGFloat vipviewy = namelabely;38 cgfloat vipvieww = 14;39 cgfloat vipviewh = 14;40 self.vipf = CGRectMake (vip Viewx, Vipviewy, VIPVIEWW, VIPVIEWH); 41 42//Set the body of frame43 cgfloat introlabelx = iconviewx;44 cgfloat intr olabely = Cgrectgetmaxy (self.iconf) + padding;45 cgsize textSize = [self sizewithstring:_weibo.text font:njtextfont m Axsize:cgsizemake (maxfloat)];46 cgfloat introlabelw = textsize.width;48 cgfloat introlabelh = textSize . height;49 self.introf = CGRectMake (Introlabelx, introlabely, Introlabelw, INTROLABELH); 51 52//Set F for the map         Rame53 cgfloat cellheight = 0;54 if (_weibo.picture) {//with map cgfloat pictureviewx = iconviewx;56 CGFloat pictureviewy = Cgrectgetmaxy (self.introf) + padding;57 cgfloat picturevieww = 100;58 CGFloat pict       UREVIEWH = 100;59  Self.pictruef = CGRectMake (pictureviewx, Pictureviewy, PICTUREVIEWW, PICTUREVIEWH); 60 61//Calculate Row Height 62 Self.cellheight = Cgrectgetmaxy (SELF.PICTRUEF) + padding;63}else64 {65//row height with no mapping case self.ce Llheight = Cgrectgetmaxy (self.introf) + padding;67}68 69}70 71/**72 * Calculate the width and height of text *74 * @param str needs to be computed Text in * * @param font text display fonts *78 * @param maxSize Text Display range of the true width of the text */80-(cgsize) sizewithstring :(NSString *) str font: (Uifont *) font maxSize: (cgsize) maxSize81 {nsdictionary *dict = @{nsfontattributename:font}; 83//If future computed text ranges beyond the specified range, returns the specified range 84//If the future computed text is less than the specified range, the return is the true range of cgsize size = [str boundingrectw Ithsize:maxsize options:nsstringdrawinguseslinefragmentorigin attributes:dict context:nil].size;86 return size;87} @end

Master Controller

NJVIEWCONTROLLER.M file

1 #import "NJViewController.h" 2 #import "NJWeibo.h" 3 #import "NJWeiboCell.h" 4 #import "NJWeiboFrame.h" 5 6 @interface Njviewcontroller () 7 @property (nonatomic, strong) Nsarray *statusframes; 8 @end 9 @implementation NJViewController11 #pragma mark-Data source Method-(Nsinteger) TableView: (UITableView *) Tablevie W numberofrowsinsection: (Nsinteger) section15 {return self.statusframes.count;17}18-(UITableViewCell *) tabl Eview: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexPath21 {Njweibocell *cell = [Njweibocell C   Ellwithtableview:tableview]; //equivalent to a cell initialization operation23//3. Set data Cell.weiboframe = Self.statusframes[indexpath.row]; //lazy Loading takes the model data to the cell's property Weiboframe (the Class object), and then calls the Set method
26//4. Return cell;28}29 #pragma mark-lazy load-(Nsarray *) statusFrames31 {if (_statusframes = nil) {NSString *fullpath = [[NSBundle mainbundle] pathforresource:@ "Statuses.plist" oftype:nil];34 NSArray *dictarray = [Nsarray arraywithcontentsoffile:fullpath];35 nsmutablearray *models = [Nsmutablearray ArrayWithCapac ity:dictarray.count];36 for (nsdictionary *dict in Dictarray) {37//Create Model 38Njweibo *weibo = [Njweibo weibowithdict:dict]; Model Data Transformation39//Create frame model based on model data njweiboframe *WBF = [[Njweiboframe alloc] init];41 Wbf.weibo = weibo;42 [Models addobject:wbf];44}45 self.statusframes = [Models copy];46 }47 return _statusframes;48}49 #pragma mark-Proxy Method-(CGFloat) TableView: (UITableView *) TableView Heightforrowa Tindexpath: (Nsindexpath *) indexPath52 {//NSLog (@ "Heightforrowatindexpath"); 54//Remove the corresponding navigation frame model, NJWEIBOFR Ame *WBF = self.statusframes[indexpath.row];56 NSLog (@ "height =%f", wbf.cellheight); return wbf.cellheight;58} -(BOOL) prefersStatusBarHidden61 {yes;63}64 @end
Summary: A data model Weibo is defined in the Weiboframe class, and a frame model is defined in the cell class, which is equivalent to the cell owning frame and model micro-blog, and setting the data mainly through the Set method.

Iv. Additional Information

Since the system-provided tableview may not meet our development needs, we often ask that we be able to customize the TableView.

There are two ways to customize TableView, one is to create using Xib, and one is to create it in a pure code way.

For the same style of tableview, it is usually created with xib, and for a different height, the content is not exactly the same and is usually customized with pure code.

Five, summary

First,the use of UITableView steps

The use of UITableView is only a simple three-step process:

1. Tell how many sets of data are in total

Method:-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView;

2. Tell each group how many lines are in total

Method:-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section;

3. Set each group per row (cell)

Method:-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath;

Ii. Description of Use

1. How many sets of data and how many rows are usually related to data, in development data is usually stored in the plist file and needs to be loaded into the project (model) in a certain way.

2. Set each row of each group, say simple point is to set the TableView in each cell.

There are three steps to setting up a cell:

(1) Create a cell (you need to consider performance, recycle the cell, pay attention to how the cache is handled)

(2) Setting data for cell

(3) Returns a cell

There are three ways to set up a cell:

(1) Setup with system-provided Tableviewcell

(2) through Xib custom Tableviewcell, applicable to raised here consistent, such as the group purchase display interface

(3) Through pure code custom Tableviewcell, applicable to gaps, such as performance is not the same, some cells have a property, and some cells do not, such as Weibo display interface

Third, custom Tableviewcell

1. To customize a view by using the Xib file

(1) Create a new Xib file that describes a view's internal

(2) Create a new custom class, the custom class needs to inherit from the system comes with the view, inherits from which class, depends on the xib and the object's class

(3) The type of the new class is best aligned with the Xib file name

(4) wiring the Xib control and the. m file of the custom class

(5) Provides a method of a class to return a created custom iview (masking the process of loading from xib)

(6) Provide a model attribute to allow the outside world to pass model data

(7) Override the setter method of the Model property, where the model data is presented to the corresponding child controls

2. Customizing the cell by way of code

(1) New? A class that inherits from UITableViewCell

(2) Rewrite Initwithstyle:reuseidentifier: Method

Add all the child controls that need to be displayed (you don't need to set the child control's data and frame, and the child controls are added to the Contentview)

One-time property setting for child controls (some properties need to be set only once, such as fonts \ fixed images)

(3) 2 models available

Data model: Storing text data \ Picture data

Frame model: The height of the Frame\cell that holds the data model \ All child controls

(4) Cell has a frame model (do not have a data model directly)

(5) Override the setter method of the Frame model property: Set the child control's display data and frame in this method

(6) The initialization of frame model data has been taken by lazy loading (each cell corresponding frame model data is loaded only once)

Iv. steps to use the agent

(1) Find out who is Who's agent first (delegate)

(2) Define proxy protocol, naming specification for protocol Name: control class name + Delegate

(3) Defining proxy methods

Proxy methods are generally defined as @optional

Proxy method names begin with the control name

The proxy method has at least 1 parameters, passing the control itself out

(4) Set proxy (Delegate) object (for example myview.delegate = xxxx;)

Proxy Object Compliance Protocol

The implementation method of the Proxy object Implementation protocol

(5) At the right time to adjust the proxy method of the proxy object (delegate), notify the agent what's going on

(Do you know if the agent implemented the agent before tuning?)

iOS Development UI article-implement a simple microblogging interface layout with pure code custom UITableViewCell

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.