美文网首页
iOS开发系列:UITableView(解析)

iOS开发系列:UITableView(解析)

作者: 为你哭泣我 | 来源:发表于2016-07-31 23:54 被阅读0次

UITableView中每行数据都是一个UITableViewCell,在这个控件中为了显示更多的信息,iOS已经在其内部设置好了多个子控件以供开发者使用,如果系统样式的cell不能满足程序员需求是我们可以创建一个子类去自定义.我们查看UITableViewCell的声明文件可以发现在内部有一个UIView控件,(contentView,作为其他元素的父控件).

数据源:由于iOS是遵循MVC模式设计的,很多操作都是通过代理和外界沟通的,但对于数据源控件除了代理还有一个数据源属性,通过它和外界进行数据交互。 对于UITableView设置完dataSource后需要实现UITableViewDataSource协议,在这个协议中定义了多种 数据操作方法. 一般通过创建一个模型(懒加载)的方式去加载数据.

数据源方法:

#pragma mark 返回组数

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

return 1;(默认1)

}

#pragma mark 返回每组行数

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

return group1.contacts.count;

}

#pragma mark返回每行的单元格

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

//1.创建cell

//2.设置数据

//3.返回cell

return cell;

}

#pragma mark 返回每组头标题名称

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

return group.name;

}

#pragma mark 返回每组尾部说明

-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{

return group.detail;

}

代理:

当发现单元格高度、分组标题高度以及尾部说明的高度都需要调整,此时就需要使用代理方法。UITableView代理方法有很多,例如监听单元格显示周期、监听单元格选择编辑操作、设置是否高亮显示单元格、设置行高等。

1.设置行高

#pragma mark - 代理方法

#pragma mark 设置分组标题内容高度

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

if(section==0){

return 50;

}

return 40;

}

#pragma mark 设置每行高度(每行高度可以不一样)

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

return 45;

}

#pragma mark 设置尾部说明内容高度

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

return 40;

}

2.监听用户点击方法:

#pragma mark 点击行

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

_selectedIndexPath=indexPath;

}

#pragma mark 窗口的代理方法,用户保存数据

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

}

}

#pragma mark 重写状态样式方法

-(UIStatusBarStyle)preferredStatusBarStyle{

return UIStatusBarStyleLightContent;

}

UITableViewCell

1.自带的UITableViewCell

UITableViewCell是构建一个UITableView的基础,在UITableViewCell内部有一个UIView控件作为其他内容的容器,它上面有一个UIImageView和两个UILabel,通过UITableViewCellStyle属性可以对其样式进行控制。

2.自定义UITableViewCell

定义一个TableViewCell实现UITableViewCell,一般实现自定义UITableViewCell需要分为两步:第一初始化控件;第二设置数据,重新设置控件frame。原因就是自定义Cell一般无法固定高度,很多时候高度需要随着内容改变。此外由于在单元格内部是无法控制单元格高度的,因此一般会定义一个高度属性用于在UITableView的代理事件中设置每个单元格高度。

相关文章

网友评论

      本文标题:iOS开发系列:UITableView(解析)

      本文链接:https://www.haomeiwen.com/subject/tagmjttx.html