UITableView的基本概念
- UITableView是用于展示列表信息的非常方便与常用的工具.
- UITableView是UISscrollView的子类,因此具有能够滑动的特性,能够上下滑动,同时在cell是可编辑的情况下,能向左滑动
UITableView的基本属性
创建UITableView
UITableView* tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
列表样式
- UITableViewStylePlain(常规表视图)
- UITableViewStyleGrouped(分区分组视图)
- UITableViewStyleInsetGrouped(圆角分区视图)
遵守协议
- 使用时应遵守协议<UITableViewDelegate,UITableViewDateSource>
tableView.delegate = self;
tableView.dataSource = self;
- 设置分区数量
//设置分区数量
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
- 设置某一分区的行数
//设置某一分区的行数,section返回的是当前分区,根据当前分区设置分区行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 2;
}
- 设置某一分区某一行的高度
//设置某一分区某一行的高度,indexPath.section是当前分区,indexPath.row是行
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 44;
}
- 设置每一行里面的内容
需要注意的是 tableView 必须使用重用机制 , 当cell滑出屏幕的时候 cell会被系统回收,在下面cell将要显示时会调用之前回收的cell,这样就不必每次都创建销毁,节省内存同时节省时间,如果不使用重用机制,每次都创建新的cell 是非常消耗内存和性能的,因此,使用重用是非常非常重要的
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//展示很多数据的时候,避免每次滑动创建新的对象,应判断是否存在再创建对象,节省资源消耗
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
if (cell==nil) {
cell = [[UITableViewCell alloc]init];
}
cell.textLabel.text = [NSString stringWithFormat:@"%@",array[indexPath.section*2+indexPath.row]];
return cell;
}
}
成员变量
- 设置分割线的长度
tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
- 设置背景颜色
tableView.backgroundColor = [UIColor redColor];
类方法
- 设置section头部高度(heightForHeaderInSection)
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 10;
}
- 设置section尾部高度(heightForFooterInSection)
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 10;
}
- 设置section头部视图(viewForHeaderInSection)
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView* view = [[UIView alloc]init];
view.backgroundColor = [UIColor blueColor];
return view;
}
- 设置section尾部视图(viewForFooterInSection)
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
UIView* view = [[UIView alloc]init];
view.backgroundColor = [UIColor redColor];
return view;
}
- 设置某一行的功能按钮
UITableViewCellEditingStyleNone(无样式)
UITableViewCellEditingStyleDelete(删除按钮)
UITableViewCellEditingStyleInsert(插入按钮)
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section) {
return UITableViewCellEditingStyleInsert;
}else{
return UITableViewCellEditingStyleDelete;
}
}
- 设置索引
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return @[@"A",@"B",@"C",@"D",@"E",@"F",@"G"];
}