One, custom cell
- Why you need a custom cell: The system-provided cell does not meet complex styles, so: custom cells and custom views create a cell that fits our needs and uses this cell. As shown in these cells are implemented by custom cell styles:
- To customize the cell:
1. First create a class that inherits from UITableViewCell: (This is a custom cell for a simple address book)
@interface Roottableviewcell:uitableviewcell // Contact head like @property (nonatomic, Strong) Uiimageview *Headerimageview; // Contact person Name label@property (Nonatomic, Strong) UILabel *Namelabel; // the label of the phone number@property (nonatomic, Strong) UILabel *Phonelabel; @end
2. Implementation of the UITableViewCell initialization method:
@implementationRoottableviewcell-(Instancetype) Initwithstyle: (Uitableviewcellstyle) style Reuseidentifier: (NSString *) reuseidentifier{ Self=[Super Initwithstyle:style Reuseidentifier:reuseidentifier]; if(self) {//initializing a child view[self initlayout]; } returnSelf ;}- (void) initlayout{//1. AvatarSelf.headerimageview = [[Uiimageview alloc] Initwithframe:cgrectmake ( -,Ten, -, -)];//Self.headerImageView.backgroundColor = [Uicolor orangecolor];Self.headerImageView.layer.masksToBounds =YES; Self.headerImageView.layer.cornerRadius= -; //The cell provides a Contentview property that is specifically designed to customize the cell to prevent layout clutter in the cell layout, and if it is a custom cell, remember to add the child control to the Contentview[Self.contentview AddSubview:self.headerImageView]; //2. NameSelf.namelabel = [[UILabel alloc] Initwithframe:cgrectmake (Cgrectgetmaxx (self.headerImageView.frame) +Ten, Cgrectgetminy (Self.headerImageView.frame), -, +)];//Self.nameLabel.backgroundColor = [Uicolor redcolor];[Self.contentview AddSubview:self.nameLabel]; //3. Phone numberSelf.phonelabel = [[UILabel alloc] Initwithframe:cgrectmake (Cgrectgetminx (Self.nameLabel.frame), Cgrectgetmaxy ( Self.nameLabel.frame) + -, $, +)];//Self.phoneLabel.backgroundColor = [Uicolor greencolor];[Self.contentview AddSubview:self.phoneLabel]; }
- Attention:
- Make sure that all of the sub-views you want to add are created in the initialization method of the custom cell, and because of the reuse mechanism of the uitableview, a cell will not go through the initialization method when it is first created and used for the next display, which avoids duplicate creation of the child view.
- After the child view of the cell is created successfully, the child view is set to the property, similar to the Textlabel and Detailtextlabel properties that are UITableViewCell. It is easy to assign values to custom views in the UITableView protocol.
Second, the use of the Model type Object
- Model class Overview:
- The model class is primarily designed to provide us with data, which is simply a custom class that inherits from the NSObject called model. (The KVC learned in the previous OC is to help us convert the dictionary to the Model class.) )
- Use the model class to hold data in a custom cell:
- First create the model class and inherit from the NSObject
- And then add the corresponding property in the dictionary
- Assigning a dictionary to model by KVC in a view controller
- Add the model object to the array and refresh the TableView
// set up model storage data @interface Contact:nsobject // name @property (nonatomic, copy) NSString *name; // Mobile number @property (nonatomic, copy) NSString *PhoneNumber; // Picture name @property (nonatomic, copy) NSString *imageName; @end
#import "RootTableViewController.h"#import "Contact.h"#import "RootTableViewCell.h"@interfaceRoottableviewcontroller ()//declare a large array to hold all contacts@property (nonatomic, strong) Nsmutablearray *Allcontactsarray;@end@implementationRoottableviewcontroller//lazy Loading (overriding getter method)-(Nsmutablearray *) allcontactsarray{if(_allcontactsarray = =Nil) {_allcontactsarray=[Nsmutablearray array]; } return_allcontactsarray;}- (void) viewdidload {[Super viewdidload]; Self.title=@"Contacts"; Self.navigationController.navigationBar.barTintColor=[Uicolor Lightgraycolor]; [Self handledata];}- (void) handledata{//Read plist fileNsmutablearray *array =[nsmutablearray arraywithcontentsoffile:[[nsbundle Mainbundle] PathForResource:@"Contacts"OfType:@"plist"]]; //Convert the data you want to display into a model object for(Nsdictionary *contactdictinchArray) { Contact*contact =[Contact alloc] init]; //assigning values using KVC[Contact Setvaluesforkeyswithdictionary:contactdict]; //Store contact model in a large array[Self.allcontactsarray addobject:contact]; } }- (void) didreceivememorywarning {[Super didreceivememorywarning]; }#pragmaMark-table View Data source-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView {returnSelf.allContactsArray.count;}-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {return 1;}-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{//Create a constant identifier StaticNSString *identifier =@"Cell"; //to find reusable cells from the reuse queueRoottableviewcell *cell =[TableView Dequeuereusablecellwithidentifier:identifier]; //determine if there are no cells to reuse, create if(!cell) {Cell=[[Roottableviewcell alloc] Initwithstyle:uitableviewcellstylesubtitle reuseidentifier:identifier]; } //Setting up data//Remove Model ObjectContact *contact =Self.allcontactsarray[indexpath.section]; Cell.headerImageView.image=[UIImage ImageNamed:contact.imageName]; Cell.nameLabel.text=Contact.name; Cell.phoneLabel.text=Contact.phonenumber; Cell.selectionstyle=Uitableviewcellselectionstylenone; returncell;}-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{return -; }- (void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) indexpath{[TableView Deselectrowatindexpath:indexpath Animated:yes]; }@end
3. Operating effects such as:
Three, a variety of cell mixed use
- A reuse identifier can only be used for a cell style, and different cells need to be differentiated based on different reuse identifiers, while the distinction of reuse identifiers needs to be divided according to different circumstances, such as:
- Model Attribute division (different data content, such as a Type field in a data, 1 for the picture type, 0 for the text type, etc.)
- Fixed rows show different cell types
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {StaticNSString *identifier1 =@"Labelcell"; StaticNSString *identifier2 =@"Imagecell"; person*person =Self.allpersonsarray[indexpath.row]; if([Person.type isequaltostring:@"1"]) {Lablecell*cell =[TableView dequeuereusablecellwithidentifier:identifier1 Forindexpath:indexpath]; Cell.nameLabel.text=Person.name; Cell.statusLabel.text=Person.status; returncell; }Else{Imageviewcell*cell =[TableView dequeuereusablecellwithidentifier:identifier2 Forindexpath:indexpath]; Cell.nameLabel.text=Person.name; Cell.statusLabel.text=Person.status; Cell.myImageView.image=[UIImage ImageNamed:person.imageName]; returncell; } }
Iv. cell self-adapting height
-
- way two kinds:
- Span style= "FONT-SIZE:16PX;" > text Adaptive height: Sets the label height
- < Span style= "font-family: the song Body;" > image Adaptive Height: scale proportionally to the width of the image
-
@interface Calculatetextheight:nsobject // declares the class method used to calculate the text height + (cgfloat) Calculatetextheightwithtext: (NSString *) text *) font; + (CGFloat) Imageheightwithimage: (UIImage *) image; @end
- The specific implementation
@implementationCalculatetextheight+ (CGFloat) Calculatetextheightwithtext: (NSString *) text font: (Uifont *) font{//The method of finding text height in iOS7.0, returning the height of a cgrect//The first parameter, a screen width, 10000 high textCgsize size = Cgsizemake ([UIScreen mainscreen].bounds.size.width,10000); //The second parameter, set to line height as a single//The third argument, judging by the font heightCGRect rect =[Text boundingrectwithsize:size options:nsstringdrawinguseslinefragmentorigin attributes:@{ Nsfontattributename:font} Context:nil]; returnRect.size.height; }+ (CGFloat) Imageheightwithimage: (UIImage *) image{//get the width and height of the pictureCGFloat width =Image.size.width; CGFloat height=Image.size.height; //get the width and height ratio and screen width floati = height/width; floatj =[UIScreen mainscreen].bounds.size.width; CGFloat x= i *J; returnx;}@end
- There is also a small bug, if the above screen width high ratio with cgfloat receive or return directly, will produce the following situation: Some pictures will make the program run in the process of width to 0, causing the program to crash. (Small master or beginner iOS, so do not know whether it is a bug or my data processing problems, if there is a big God know the reason can comment leave contact information. )
+ (CGFloat) Imageheightwithimage: (UIImage *) image{//get the width and height of the pictureCGFloat width =Image.size.width; CGFloat height=Image.size.height; //get the width and height ratio and screen width//the width and height ratio of the screen is received with CGFloatCGFloat i = height/width; CGFloat J=[UIScreen mainscreen].bounds.size.width; CGFloat x= i *J; returnx;//or return directly//return height/width *[uiscreen mainscreen].bounds.size.width;}
iOS Learning UI Custom cell