UITableViewCell自定义
cell分区的行高自适应
采用类方法,是为了在返回cell的行高时调用
// 计算字符串的高度
+ (CGFloat)cellHeightForModel:(NewsModel *)model{
// 创建字体大小的字典
// 字面量初始化
NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:16]};
CGRect textRect = [model.summary boundingRectWithSize:CGSizeMake(kScreenWidth - kMargin * 2, 6666) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];
return textRect.size.height;
}
返回cell行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
// 计算高度
CGFloat labelHeight = [NewsTableViewCell cellHeightForModel:self.newsArray[indexPath.row]];
// 上边距 toplabel + 中间距离 + 动态label高度 + 下边距
return 20 + 40 + 20 + labelHeight + 40;
}
解决cell的复用性问题
划出屏幕的cell在被重用时,重新赋值了
在model类里添加状态属性
// 标识选中的状态
@property (nonatomic, assign) BOOL isSelected;
在数据处理过程中为模型对象添加状态属性值
// 数据处理
- (void)dataProcess{
NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsData" ofType:@"plist"];
self.dataDic = [NSMutableDictionary dictionaryWithContentsOfFile:path];
NSString *key = @"news";
NSArray *dataArray = self.dataDic[key];
self.newsArray = [NSMutableArray array];
for (NSDictionary *dic in dataArray) {
NewsModel *model = [[NewsModel alloc] init];
[model setValuesForKeysWithDictionary:dic];
// 给点击状态加一个初值
model.isSelected = NO;
[self.newsArray addObject:model];
[model release];
}
}
在模型属性的set方法里根据不同的状态赋不同的值
- (void)setModel:(NewsModel *)model{
if (_model != model) {
[_model release];
_model = [model retain];
}
self.titleLabel.text = model.title;
self.summaryLabel.text = model.summary;
// 利用model中的点选状态解决cell复用的问题
// 需要背刺被复用的cell 再进行一次与状态对应对应的赋值
if (model.isSelected == YES) {
self.imageV.image = [UIImage imageNamed:@"select"];
}else{
self.imageV.image = [UIImage imageNamed:@"cancel"];
}
// 计算字符串的高度
CGFloat summaryHeight = [NewsTableViewCell cellHeightForModel:model];
// 改变一下label的高度
self.summaryLabel.height = summaryHeight;
// 多行显示
self.summaryLabel.numberOfLines = 0;
// 设置字体大小
self.summaryLabel.font = [UIFont systemFontOfSize:16];
}