iOS Basics-UITableView through case studies (UP)
For UITableView a lot of knowledge points, because it is one of the most used iOS controls, I will do my best efforts and language organization, will all the knowledge points in place, today to achieve the
Spit Groove
- Compared to Android, it can be said that the implementation of the ListView is almost the same as Recyclerview.
- Android seems a bit more complicated than iOS, because iOS is mostly packaged, which is good for iOS
- The name of the iOS method can only be said to be long and smelly.
Knowledge points include
- UITableView's Uitableviewdatasource
- UITableView's Uitableviewdelegate
- The reuse of UITableView cells
First, the preparatory work
1. Prepare the data source (plist)
2. layout file
second, model read data
Analyze the format of the plist data, then create the corresponding object model and provide the appropriate initialization method, which is a classic step in MVC
- Special Note: Properties in the @property can not use the weak property, otherwise it will be recycled in the UITableView reuse mechanism, causing the screen to not appear
@interface heromodel : nsobject @property (nonatomic , strong ) nsstring *icon; @property (nonatomic , strong ) nsstring *intro; @property (nonatomic , strong ) nsstring *name;-(instancetype) initwithdict: ( Nsdictionary *) dict;+ (instancetype) heromodelwithdict: (nsdictionary *) Dict @end
Implement initialization method in M file, convert dictionary to object in method
@implementation HeroModel-(instancetype)initWithDict:(NSDictionary *)dict{ if(self = [super init]){ [self setValuesForKeysWithDictionary:dict]; } returnself;}+(instancetype)HeroModelWithDict:(NSDictionary *)dict{ return [[self alloc]initWithDict:dict];}@end
Third, UITableView
1. Declaring a delegate agent, declaring a property
To UITableView have data, you must use its delegate proxy method to display the data in UITableView
@interface ViewController ()<UITableViewDataSource>//存放数据的可变数组@property (strongnonatomicNSMutableArray *dataArray;//tableview@property (strongnonatomicIBOutletUITableView *tableView;@end
2, the implementation of the conversion of attributes
There is no doubt that by lazy loading the plist content into a model into a mutable array of our declarations
#pragma replication Get method#pragma lazy load, read plist file and convert to model- (Nsmutablearray*) dataarray{if(Nil= = _dataarray) {//Initialize array_dataarray = [NsmutablearrayArray];//Get plist file path NSString*path = [[NSBundlemainbundle]pathforresource:@"Heros.plist"OfType:Nil];//Read plist file contents Nsarray*temparray = [NsarrayArraywithcontentsoffile:path];//traverse the contents of the Plist file and store it in a mutable array for(nsdictionary* Dict in Temparray) {Heromodel *heromodel = [Heromodel heromodelwithdict:dict]; [_dataarray Addobject:heromodel]; } }//Return return_dataarray;}
3. Delivery Commission
//交付委托_self;
4, the method of implementing the agent
By implementing the Uitableviewdatasource proxy method, the data is displayed, similar to the adapter of the ListView
#pragma uitableviewdatasource Delegate method#pragma returns the total number of groups-(Nsinteger) Numberofsectionsintableview: (UITableView*) tableview{//Return 1 groups by default return 1;}#pragma uitableviewdatasource Delegate method#pragma returns a group by how many rows-(Nsinteger) TableView: (UITableView*) TableView numberofrowsinsection: (Nsinteger) section{//number of returned data return Self. DataArray. Count;}#pragma uitableviewdatasource Delegate method#pragma returns the contents of each row of item-(UITableViewCell*) TableView: (UITableView*) TableView Cellforrowatindexpath: (Nsindexpath*) indexpath{//Create a TableView item UITableViewCell*cell = [[UITableViewCellAlloc]initwithstyle:uitableviewcellstylesubtitle Reuseidentifier:Nil];//Indexpath the corresponding model by the line property of theHeromodel *heromodel = _dataarray[indexpath. Row];//Set Text informationCell. Textlabel. Text= Heromodel. Name;//Set Picture information UIImage*image = [UIImageImagenamed:heromodel. Icon]; Cell. ImageView. Image= Image;//Set Detail textCell. Detailtextlabel. Text= Heromodel. Intro;//Set the rightmost arrowCell. Accessorytype= Uitableviewcellaccessorydisclosureindicator;//Return returnCell;}
There are two ways to display ①uitableview, which can be set in storyboard
1.plain: Data tiled display, no gaps in the middle, the header of the array has a suspension effect
2.group: Data grouping display with gaps in the middle
②uitableviewdatasource The delegate method, the program executes in the following order
- Numberofsectionsintableview: How many groups of impressions are in the data (optional implementation, default return of 1 groups)
- Numberofrowsinsection: How many rows per group in the data (must be implemented, otherwise it will be an error)
- Cellforrowatindexpath: The contents of each line in the data (must be implemented, otherwise it will be an error)
Four styles of ③uitableviewcell
1.UITableViewCellStyleDefault
2.uitableviewcellstylevalue1
3.uitableviewcellstylevalue2
4.UITableViewCellStyleSubtitle
Five styles of ④cell.accessorytype, not much to explain
- Uitableviewcellaccessorynone
- Uitableviewcellaccessorydisclosureindicator
- Uitableviewcellaccessorydetaildisclosurebutton
- Uitableviewcellaccessorycheckmark
- Uitableviewcellaccessorydetailbutton
5, Uitableviewdatasource other agent methods
These two proxy methods will be more clearly displayed in the group style.
#pragma UITableViewDataSource委托方法#pragma 返回tableview中头部的标题-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ return @"header";}#pragma UITableViewDataSource委托方法#pragma 返回tableview中底部的标题-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{ return @"footer";}
6. Cell Reuse
- The cell is the same as the ListView item, and it is the one that will be reused for the item.
- Reuse is mostly used to reuse identifiers.
- In the Cellforrowatindexpath method, change the cell's creation code to
//重用标识符,需要用static修饰,避免多次分配内存给NSStringstaticNSString *identifier = @"h1";//从缓存池中取出tableview的itemUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];//创建cellif(nil == cell){ cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];}
7, the TableView property introduction
- _tableview.separatorcolor: Split Line Color
- _tableview.separatorinset: Split Line indentation
- _tableview.separatorstyle: Split Line type
- _tableview.allowsmultipleselection: Allow option multiple selection
- _tableview.tableheaderview: Can add a view in the head
- _tableview.tablefooterview: You can add a view at the bottom
- _tableview.sectionheaderheight: interval for each group
8. Implement Cell Click events
① Declaration of Entrustment and delivery
The cell's Click event is the implementation method in Uitableviewdelegate
//声明委托@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>//交付委托_tableView.delegateself;
② Implement Click event function
#pragma UITableViewDelegate委托方法#pragma 反选数据时调用-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{}#pragma UITableViewDelegate委托方法#pragma 选择数据时调用-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{}
9, to achieve the cell editing mode and cell increase insertion
The cell's edit mode and cell insertion are also implemented in Uitableviewdelegate.
#pragma uitableviewdelegate Delegate method#pragma decide which line to enter in edit mode-(BOOL) TableView: (UITableView*) TableView Caneditrowatindexpath: (Nsindexpath*) indexpath{if(Indexpath. Row==2){return NO; }Else{return YES; }}#pragma uitableviewdelegate Delegate method#pragma click on the delete and insert callback function, which also turns on the slide-by-slip function-(void) TableView: (UITableView*) TableView Commiteditingstyle: (uitableviewcelleditingstyle) Editingstyle Forrowatindexpath: (Nsindexpath*) indexpath{if(Editingstyle = = Uitableviewcelleditingstyledelete) {//Delete the data in the array[_dataarray Removeobjectatindex:indexpath. Row];//tableview Completing the delete operation, updating the UI[_tableview Deleterowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationleft]; }Else if(Editingstyle = = Uitableviewcelleditingstyleinsert) {//Simulation Add DataHeromodel *hero = [[Heromodel alloc]init]; Hero. Name= @"Ice shooter";//Add to array[_dataarray Insertobject:hero Atindex:indexpath. Row];//tableview Completing the add operation, updating the UI[_tableview Insertrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationright]; }}#pragma uitableviewdelegate Delegate method#pragma decide which line of editing mode to open is insert mode or delete mode-(Uitableviewcelleditingstyle) TableView: (UITableView*) TableView Editingstyleforrowatindexpath: (Nsindexpath*) indexpath{if(Indexpath. Row<=5){returnUitableviewcelleditingstyleinsert; }Else{returnUitableviewcelleditingstyledelete; }}#pragma uitableviewdelegate Delegate methodDelete button text display in #pragma delete mode-(NSString*) TableView: (UITableView*) TableView Titlefordeleteconfirmationbuttonforrowatindexpath: (Nsindexpath*) indexpath{return@"Blind Kerak.";}
How to delegate ①uitableviewdelegate
- Caneditrowatindexpath: Which line is allowed to turn on edit mode
- Commiteditingstyle: Click on the event's callback while turning on the slide delete
- Editingstyleforrowatindexpath: Decide which line of edit mode
②indexpath Property
- Indexpath.row: Index of rows
- Indexpath.section: Index of the group
③ edit mode animation, you can see the name should be able to guess
- Uitableviewrowanimationfade
- Uitableviewrowanimationright
- Uitableviewrowanimationleft
- Uitableviewrowanimationtop
- Uitableviewrowanimationbottom
- Uitableviewrowanimationnone
- Uitableviewrowanimationmiddle
- Uitableviewrowanimationautomatic
④ Finally, just turn on edit mode
_tableView.editing = YES;
Conclusion
After learning a uitableview, the most regrettable thing is that you can't remember the method name, just remember some of the words, of course, these are the things that make perfect. There is a lot of knowledge about UITableView, and this is just a part of it, and I'm going to introduce UITableView's usage
SOURCE download
iOS Basics-UITableView through case studies (UP)