cell 的使用
cell的简介:
tableView:cellForRowAtIndexPath://初始化每一行
* UITableViewCell内部有个默认的子视图:contentView,contentView是UITableViewCell所显示内容的父视图,可显示一些辅助指示视图
UITableViewCellAccessoryDisclosureIndicator UITableViewCellAccessoryDetailButton UITableViewCellAccessoryDetailDisclosureButton UITableViewCellAccessoryCheckmark
## 传统写法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // 1.定义一个cell的标识 static NSString *ID = @”czcell"; // 2.从缓存池中取出cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; // 3.如果缓存池中没有cell if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; }
// 4.设置cell的属性~~~
return cell;
}
## 新的写法
NSString *ID = @"标示";
- (void)viewDidLoad {
[super viewDidLoad];
// 注册某个重用标识 对应的 Cell类型
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1.先去缓存池中查找可循环利用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 2.设置数据
cell.textLabel.text = [NSString stringWithFormat:@"%zd行的数据", indexPath.row];
return cell;
}
2、当cell的高度不同时:
我们需要自定义cell
1.新建一个继承自UITableViewCell的类
2.重写initWithStyle:reuseIdentifier:方法
3.提供2个模型
4.cell拥有一个frame模型(不要直接拥有数据模型)
5.重写frame模型属性的setter方法: 在这个方法中设置子控件的显示数据和frame
6.frame模型数据的初始化已经采取懒加载的方式(每一个cell对应的frame模型数据只加载一次)
// 设置cell右边样式 cell.accessoryType; cell.accessoryView; // selectedBackgroundView设置选中背景优先级是比selectionStyle高 UIView *bg = [[UIView alloc] init]; bg.backgroundColor = [UIColor purpleColor]; // cell.selectedBackgroundView = bg; // //UITableViewCellSelectionStyleBlue 在iOS7之后和Gray效果相同 // cell.selectionStyle = UITableViewCellSelectionStyleBlue; // backgroundView它的优先级比backgroundColor高,并且这俩是并存 cell.backgroundView = bg; cell.backgroundColor = [UIColor yellowColor]; cell.contentView;