------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
一、UITableViewCell
1. UITableView的每一行都是一个UITableViewCell,通过dataSource的tableView:cellForRowAtIndexPath:方法来初始化每一行。
2. UITableViewCell时候UIView的子类,内部有个默认的子视图:contentView。contentView是UITableViewCell所显示内容的父视图,并负责显示一些辅助指示视图。辅助指示视图的作用是显示一个表示动作的图标,可以通过设置UITableViewCell的accessoryType来显示,默认是UITableViewCellAccessoryNone(不显示辅助指示视图),其他值如下:
* UITableViewCellAccessoryDisclosureIndicator >
* UITableViewCellAccessoryDetailDisclosureButton >带圆圈的。
* UITableViewCellAccessoryCheckmark √
二、UITableViewCell的contentView
1.contentView下默认有3个子视图,其中的2个是UILabel(通过UITableViewCell的textLabel和detailTextLabel属性访问),第3个是UIImageView(通过UITabelViewCell的imageView属性访问)。
2.UITableViewCell还有一个UITableViewCellStyle属性,用于决定使用contentView的哪些子视图,以及这些子视图在contentView中的位置:
* UITableViewCellStyleDefault :默认不显示子标题。
* UITableViewCellStyleSubttitle :显示子标题,子标题显示在标题下面。
* UITableViewCellStyleValue1 :子标题显示在标题右边。
* UITableViewCellStyleValue2 :子标题显示在标题右边,子标题字体大于标题,且图标不显示。
三、UITableViewCell对象的重用原理
1.IOS设备的内存有限,如果用UITableView显示成千上万条数据,就需要成千上万个UITableViewCell对象的话,那将会耗尽IOS设备的内存。
要解决该问题,需要重用UITableViewCell对象。
2.重用原理:当滚动列表时,部分UITableViewCell会移动窗口,UITableViewView会将窗口外的UITableViewCell放入一个对象池中,等待重用。当
UITableView要求dataSource返回UITableViewCell时,dataSource会先查看这个对象池,如果池中有未使用的UITableViewCell,dataSource会用新的数据配置这个
UITableViewCell,然后返回给UITableView,重新显示超窗口中,从而避免创建新对象。
3.还有一个非常重要的问题:有时候需要自定义UITableViewCell(用一个子类继承UITableViewCell),而且每一行用的不一定是同一种UITableViewCell
(如短信聊天布局),所以一个UITableView可能拥有不同类型的UITableViewCell,对象池中也会有很多不同类型的UITableViewCell,那么UITableView在从用
UITableViewCell时可能会得到错误类型的UITableViewCell。
4.解决方案:UITableViewCell有个NSString *reuseIndetifier属性,可以在初始化UITableViewCell的时候传入一个特定的字符串来 设置reuseIdentifier(一般用UITableViewCell的类名)。当UITableView要求dataSource返回UITableViewCell时,如果有,就重用,如果没有,就传入这个字符串标示来初始化一个UITableViewCell对象。
四、重用UITableViewCell对象
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"UITableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
cell.textLabel.text = [NSString stringWithFormat:@"Text %i", indexPath.row];
return cell;
}
五、UITableViewCell的常用属性
1.设置背景
backgroundView
2.设置被选中时的背景视图
selectedBackgroundView
3.selectionStyle属性可设置UITableViewCell被选中时的背景颜色:
UITableViewCellSelectionStyleNone 没有颜色
UITableViewCellSelectionStyleBlue 蓝色(默认)
UITableViewCellSelectionStyleGray 灰色