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

Source: Internet
Author: User
Tags ranges uikit

This article transferred from: http://www.cnblogs.com/wendingding/p/3761730.html

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

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  3 @interface njweibo:nsobject 4 @property (nonatomic, copy) NSString *te xt 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, Strong) Njweibo *weibo; 9 @property (nonatomic, strong) Njweiboframe *weiboframe;11 + (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; (void) Setweiboframe: (Njweiboframe *) weiboframe 94 _weiboframe = Weiboframe; 95 96//1 . assigning data to child controls [self settingdata];     98//2. Set frame [self settingframe];100}101 102 103/**104 * Set data for child controls */106-(void) settingData107 {108 Njweibo *weibo = Self.weiboFrame.weiBO;109 110//Set avatar 111 self.iconView.image = [UIImage imagenamed:weibo.icon];112//Set nickname 113 Self.namela Bel.text = weibo.name;114//Set vip115 if (WEIBO.VIP) {$ self.vipView.hidden = no;117 Self.namela Bel.textcolor = [Uicolor redcolor];118}else119 {self.vipView.hidden = yes;121 Self.namelabel. TextColor = [Uicolor blackcolor];122}123//set content 124 Self.introLabel.text = weibo.text;125 126//Set map 127 if (weibo.picture) {//has a map of self.pictureView.image = [UIImage imagenamed:weibo.picture];129 self . Pictureview.hidden = no;130}else131 {self.pictureView.hidden = yes;133}134}135/**136 * Set child control Pieces of frame137 */138-(void) settingFrame139 {140 141//set avatar frame142 self.iconView.frame = Self.weiboFrame.iconF        ; 143 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 frame154 155 if (self.weiboFrame.weibo.picture) {//with map 156 Self.pictureView.frame = Self.weibofra  me.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 true width 168 */169-(cgsize) sizewithstring: (NSString *) str font: (uifont *) Font maxSize: (cgsize) maxSize170 {171 Nsdictionary *dict = @{nsfontattributename:font};172//If future computed text ranges beyond the specified The range, returned is the specified range 173//If the future computed text range is less than the specified range, the return is the true range 174 cgsize size = [str boundingrectwithsize:maxsize options:n Sstringdrawinguseslinefragmentorigin 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  */34 @property (nonatomic, Strong) Njweibo *weibo;35 @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];23//3. Set Data Cell.weiboframe = self.statusframes[indexpath.row];25 26//4. Back cell;28}29 #pragma mark-lazy load-(Nsarray *) statusFrames31 {+ if (_statusframes = nil) {N sstring *fullpath = [[NSBundle mainbundle] pathforresource:@ "statuses.plist" oftype:nil];34 NSArray *dictArray = [ Nsarray arraywithcontentsoffile:fullpath];35 Nsmutablearray *mOdels = [Nsmutablearray arraywithcapacity:dictarray.count];36 for (nsdictionary *dict in Dictarray) {37 Create model Njweibo *weibo = [Njweibo weibowithdict:dict];39//Create frame model based on model data njwe Iboframe *WBF = [[Njweiboframe alloc] init];41 Wbf.weibo = weibo;42 [Models Addobje ct:wbf];44}45 self.statusframes = [Models copy];46}47 return _statusframes;48}49 #pragma mar K-Proxy Method-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexPath52 {//NSL OG (@ "Heightforrowatindexpath"); 54//Remove the corresponding navigation frame model Njweiboframe *WBF = self.statusframes[indexpath.row];56 N SLog (@ "height =%f", wbf.cellheight); return wbf.cellheight;58}59-(BOOL) prefersStatusBarHidden61 {Retu RN yes;63}64 @end

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.

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.