最近一直在用Tableview在这过程中也有了很多关于它的体会,在这里就合大家分享一下这个很普通也很重要的控件。
Tableview继承于UIScrollView,它具备所有ScrollView的属性同时也具有自己的特点,首先让我们看看TableView是如何设置的。
UITableView * atable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 416) style:UITableViewStylePlain];
[atable setBackgroundColor:[UIColor brownColor]];
// 分割线颜色
// [atable setSeparatorColor:[UIColor blackColor]];
// 把分割线设置不可见
// [atable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
// 设置行高
[atable setRowHeight:100];
[self.view addSubview:atable];
[atable release];
TableView有两个代理分别是Delegate和dataSource,在dataSource中有两个协议方法必须实现分别是
1.每个section有几个cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
2.重用池的创建
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
dataSource是UITableViewDataSource类型,主要为UITableView提供显示用的数据(UITableViewCell),指定UITableViewCell支持的编辑操作类型(insert,delete和reordering),并根据用户的操作进行相应的数据更新操作,如果数据没有更具操作进行正确的更新,可能会导致显示异常。delegate是UITableViewDelegate类型,主要提供一些可选的方法,用来控制tableView的选择、指定section的头和尾的显示以及协助完成cell 的删除和排序等功能。
delegate是UITableViewDelegate类型,主要提供一些可选的方法,用来控制tableView的选择、指定section的头和尾的显示以及协助完成cell的删除和排序等功能。
提到UITableView,就必须的说一说NSIndexPath。UITableView声明了一个NSIndexPath的类别,主要用来标识当前cell的在tableView中的位置,该类别有section和row两个属性,前者标识当前cell处于第几个section中,后者代表在该section中的第几行。
UITableView只能有一列数据(cell),且只支持纵向滑动,当创建好的tablView第一次显示的时候,我们需要调用其reloadData方法,强制刷新一次,从而使tableView的数据更新到最新状态。
上文已经提到了重用池的创建,以下就是重用池创建的具体方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//只初始化一次 创建重用池
static NSString * cellIdentify = @"chi1";
// 从重用池取可以重用的cell
MyCell* mycell = [tableView dequeueReusableCellWithIdentifier: cellIdentify];
if (!mycell) {
mycell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentify] autorelease];
// 放到哪个重用池 style有好几种样式用来设置布局
// 参数里面的属性
NSInteger row = indexPath.row;
NSInteger section = indexPath.section;
NSString * abc =[NSString stringWithFormat:@"%d%d",row,section] ;
NSLog(@"abc===%@",abc);
}
return mycell;
}
设置Cell的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
以上就是我跟大家分享的一些心得,谢谢关注!