IOS uitableview Table View (3) custom cell

Source: Internet
Author: User

1. Custom cell

2. Mixed use of multiple cells

3.cell Self-adapting height

Custom Cell is to create a UITableViewCell sub-class.

put Cell are encapsulated in subclasses, simplifying Uiviewcontroller the code in

the child view control is added to the Cell of the Contentview on

Cell How to display the controls in Model the information in?

CellDeclaration of aModeltypes of properties,Viewcontrollerin the Get toModelthePost-image assignment toCellof theModelProperties,Celloverridden inModelof theSettermethod, putModelthe contents of the object are re-assigned to thea controlMand theVdo not communicate directly,Cresponsible forMand theVcommunication between the

usually we will be in Tableview:cellforrowatindexpath: methods are based on different

Model to decide what type of Cell each of these types of Cell to define a different reuse identifier Cell Reuse is used to reuse the identity of the queue from the reuse of what kind of Cell

The code is as follows:

Build a model

#import <Foundation/Foundation.h> @interface student:nsobject@property (nonatomic,strong) NSString *name;@ Property (Nonatomic,strong) NSString *age; @property (Nonatomic,strong) nsstring *tel; @property (Nonatomic,strong) NSString *qq; @property (Nonatomic,strong) nsstring *description; @property (Nonatomic,strong) nsstring *sex; @property ( Nonatomic,strong) NSString *icon; @end
#import "Student.h" @implementation student//if no corresponding key value is found go this way-(void) SetValue: (ID) value Forundefinedkey: (nsstring *) key{} @end
Create a file plist to hold the data
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE plist Public "-//apple//dtd plist 1.0//en" "Http://www.apple.com/DTDs/PropertyList-1.0.dtd" ><plist Version= "1.0" ><array><dict><key>name</key><string> Xiao Ming </string><key >age</key><string>18</string><key>tel</key><string>18888888</string ><key>qq</key><string>700000</string><key>sex</key><string> female </ String><key>description</key><string> is just an instant, no face that is eternal </string><key>icon</ Key><string>lishijie.png</string></dict><dict><key>name</key><string > Small Scented </string><key>age</key><string>18</string><key>tel</key>< String>110</string><key>qq</key><string>123456</string><key>sex</key ><string> female </string><key>description</key><striNg> is just an instant, no face that is eternal </string><key>icon</key><string>leixin.png</string></ Dict></array></plist>

Create a Roottableviewcontroller
#import "RootTableViewController.h" #import "RootTableViewCell.h" #import "Student.h" #import "GirlTableViewCell.h" @ Interface Roottableviewcontroller ()//used to store how many arrays of @property (Nonatomic,strong) Nsmutablearray *grouparray;@ End@implementation roottableviewcontroller-(ID) Initwithstyle: (uitableviewstyle) style{self = [Super InitWithStyle:    Style]; if (self) {//Custom initialization} return to self;}    -(void) viewdidload{[Super Viewdidload];    Path Fetch data NSString *path = [[NSBundle mainbundle] pathforresource:@ "student" oftype:@ "plist"];    Temporary access to data nsarray *temparray = [Nsarray Arraywithcontentsoffile:path];    Temporary packet storage Nsmutablearray *arr = [Nsmutablearray array];        For (Nsdictionary *dict in Temparray) {Student *stu = [[Student alloc] init];        Match key in Stu [Stu Setvaluesforkeyswithdictionary:dict];    [Arr Addobject:stu];           }//Add the temporary group to the total score Group Self.grouparray = [Nsmutablearray Arraywithobject:arr]; }-(void) Didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} #pragma mark-table View data source-(Nsinteger) Numberofsectionsintableview: (UITableView *) tableview{//Return the N    Umber of sections. return self.groupArray.count;} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{//Return the number of rows    The section. return [self.grouparray[section] count];} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{Student *st        U = Self.grouparray[indexpath.section][indexpath.row];        if ([Stu.sex isequaltostring:@ "Male"]) {nsstring *cell_id [email protected] "Cell_boy";        Roottableviewcell *cell = [TableView dequeuereusablecellwithidentifier:cell_id]; if (nil = = cell) {cell = [[Roottableviewcell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:        CELL_ID];              }  Cell.textLabel.text = @ "Test data";                Cell.nameLabel.text = [Self.grouparray[indexpath.section][indexpath.row] name];                Cell.telLabel.text = [Self.grouparray[indexpath.section][indexpath.row] tel];        Cell.descriptionLabel.text = [Self.grouparray[indexpath.section][indexpath.row] description]; Define Descriptionlabel Fram//[roottableviewcell TextHeight:stu.description] Call method to calculate the height of the text Cell.descriptionlabel. frame = CGRectMake (cell.descriptionlabel.frame.origin.x, CELL.DESCRIPTIONLABEL.FRAME.ORIGIN.Y,        Cell.descriptionLabel.frame.size.width, [Roottableviewcell textHeight:stu.description]);        Calculate text Height Method Two:////Get the height of the label//CGRect Temprect = cell.descriptionlabel.frame;////temp height equals the height of the input text// TempRect.size.height = [Roottableviewcell textheight:stu.description];////Fram the temp to label//CELL.D       Escriptionlabel.frame = temprect;////cell.descriptionLabel.numberOfLines = 0;                 return cell;        }else{nsstring *cell_id = @ "Cell_girl";                Girltableviewcell *cell = [TableView dequeuereusablecellwithidentifier:cell_id]; if (nil = = cell) {cell = [[Girltableviewcell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:        CELL_ID];                        } Cell.nameLabel.text = [Self.grouparray[indexpath.section][indexpath.row] name];                Cell.telLabel.text = [Self.grouparray[indexpath.section][indexpath.row] tel];                Cell.iconImage.image = [UIImage ImageNamed:stu.icon];    return cell;            }}-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{              Student *stu = Self.grouparray[indexpath.section][indexpath.row];    if ([Stu.sex isequaltostring:@ "Male"]) {return [Roottableviewcell cellHeight:stu.description];        }else{return 100;   }     } @end 

Create
UITableViewCell
#import <UIKit/UIKit.h> @interface roottableviewcell:uitableviewcell@property (nonatomic,strong) Uiimageview * Iconimage, @property (nonatomic,strong) UILabel *namelabel, @property (nonatomic,strong) UILabel *tellabel; @property ( Nonatomic,strong) UILabel *descriptionlabel;//class method: Must know the height of the text before creating the cell display//Calculate the height of the cell//class method is created before + (cgfloat) Cellheight: (nsstring *) text;//Calculated text height + (cgfloat) TextHeight: (NSString *) astring; @end
#import "RootTableViewCell.h" @implementation roottableviewcell-(ID) Initwithstyle: (Uitableviewcellstyle) style    Reuseidentifier: (NSString *) reuseidentifier{self = [super Initwithstyle:style reuseidentifier:reuseidentifier];    if (self) {//initialization code [self addallviews]; } return self;} Calculate cell height + (cgfloat) Cellheight: (NSString *) text{//Dead value and text height return 20+60+10+20+[[self class] textheight:text];} Calculated text height + (cgfloat) TextHeight: (NSString *) astring{nsdictionary *dict = @{nsfontattributename:[uifont    SYSTEMFONTOFSIZE:17]};  Calculates the height of the text inside the font cgrect textrect = [astring boundingrectwithsize:cgsizemake ([UIScreen mainscreen].bounds.size.width-40,    Options: (Nsstringdrawinguseslinefragmentorigin) attributes:dict Context:nil]; Only use its height, so return to his height of return textRect.size.height;}    -(void) addallviews{//Avatar picture self.iconimage = [[Uiimageview alloc] init];    Self.iconImage.frame = CGRectMake (20, 20, 60, 60); Self.iconImage.backgroundColor = [UICOlor Redcolor];        [Self.contentview AddSubview:self.iconImage];    Name label Self.namelabel = [[UILabel alloc] init]; Self.nameLabel.frame = CGRectMake (Cgrectgetmaxx (self.iconImage.frame) + ten, Cgrectgetminy (Self.iconImage.frame),    SELF.BOUNDS.SIZE.WIDTH-40-SELF.ICONIMAGE.FRAME.SIZE.WIDTH-10, 25);        self.namelabel.backgroundcolor= [Uicolor Bluecolor];        [Self.contentview AddSubview:self.nameLabel];    Phone label Self.tellabel = [[UILabel alloc] init]; Self.telLabel.frame = CGRectMake (Cgrectgetmaxx (self.iconImage.frame) + ten, Cgrectgetmaxy (self.nameLabel.frame) + 10,    SELF.BOUNDS.SIZE.WIDTH-40-SELF.ICONIMAGE.FRAME.SIZE.WIDTH-10, 25);    self.tellabel.backgroundcolor= [Uicolor Bluecolor];        Self.descriptionLabel.numberOfLines = 0;        [Self.contentview AddSubview:self.telLabel];    Introduction to label Self.descriptionlabel = [[UILabel alloc] init]; Self.descriptionLabel.frame = CGRectMake (Cgrectgetminx (Self.iconImage.frame), Cgrectgetmaxy (Self.iconImage.frame) + Ten, self.bounds.size.width-40, 80);        Self.descriptionLabel.backgroundColor = [Uicolor Cyancolor];    [Self.contentview AddSubview:self.descriptionLabel]; }-(void) awakefromnib{//initialization code}-(void) setselected: (BOOL) selected animated: (BOOL) animated{[Super Set    Selected:selected animated:animated]; Configure The view for the selected state} @end

Custom cell

#import <UIKit/UIKit.h> @interface girltableviewcell:uitableviewcell@property (nonatomic,strong) Uiimageview * Iconimage, @property (nonatomic,strong) UILabel *namelabel; @property (Nonatomic,strong) UILabel *tellabel; @end

#import "GirlTableViewCell.h" @implementation girltableviewcell-(ID) Initwithstyle: (Uitableviewcellstyle) style    Reuseidentifier: (NSString *) reuseidentifier{self = [super Initwithstyle:style reuseidentifier:reuseidentifier];    if (self) {//initialization code [self addallviews]; } return self;}    -(void) addallviews{//Avatar picture self.iconimage = [[Uiimageview alloc] init];    Self.iconImage.frame = CGRectMake (20, 20, 60, 60);    Self.iconImage.backgroundColor = [Uicolor Yellowcolor];        [Self.contentview AddSubview:self.iconImage];    Name label Self.namelabel = [[UILabel alloc] init]; Self.nameLabel.frame = CGRectMake (Cgrectgetmaxx (self.iconImage.frame) + ten, Cgrectgetminy (Self.iconImage.frame),    SELF.BOUNDS.SIZE.WIDTH-40-SELF.ICONIMAGE.FRAME.SIZE.WIDTH-10, 25);            self.namelabel.backgroundcolor= [Uicolor Greencolor];        [Self.contentview AddSubview:self.nameLabel];    Phone label Self.tellabel = [[UILabel alloc] init]; Self.tellaBel.frame = CGRectMake (Cgrectgetmaxx (self.iconImage.frame) + ten, Cgrectgetmaxy (self.nameLabel.frame) + 10,    SELF.BOUNDS.SIZE.WIDTH-40-SELF.ICONIMAGE.FRAME.SIZE.WIDTH-10, 25);            self.tellabel.backgroundcolor= [Uicolor Greencolor];    [Self.contentview AddSubview:self.telLabel]; }-(void) awakefromnib{//initialization code}-(void) setselected: (BOOL) selected animated: (BOOL) animated{[Super Set    Selected:selected animated:animated]; Configure The view for the selected state} @end




IOS uitableview Table View (3) custom cell

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.