导语:
TableView的使用存在很多的技巧,如果能够巧妙的使用和封装TableView,代码的可读性和优美度会变的非常的高。
一 cell数据完美封装术
在理想状态,Tableview
的cellForRowAtIndexPath:
方法中使用cell,只需要三段代码
1.创建cell
2.给cell赋值
3.返回cell
talk is cheap,show you the code
//返回每行显示的cell
- (UITableViewCell *)tableView:(UITableView *)tableView CellForRowAtIndexPath:(NSIndexPath *)indexPath{
//1.创建可重用的自定义cell
CZGroupBuyingCell *cell = [CZGroupBuyingCell groupBuyingCellWithTableView:tableView];
//2.设置cell的内部子空间
cell.groupBuying = self.dataSource[indexPath.row];
//3.返回cell
return cell;
}
@implementation CZGroupBuyingCell
+ (instancetype)gourpBuyingCellWithTableView:(UITableView *)tableView{
Static NSString *Identifier = @"gb";
CZGroupBuyingCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
return cell;
}
- (void)setGroupBuying:(CZgroupBuying *)groupBuying{
_grouping = groupBuying;
self.titleView.text = groupBuying.title;
self.iconView.image = [UIImage imageNamed:groupBuying.icon];
}
其中的奥秘继续往下看
首先声明一个类方法用于创建cell,一个给控件赋值的方法
-
并在创建cell的方法中实现
- 创建静态字符串用语cell的标示
- 将cell放入可复用框内,并加上标示。这样当需要复用 cell时,就会自动去复用框里去寻找cell
- 另外,给cell添加一个自定义的属性,并且重写他的set方法,这样在上图中执行
cell.groupBuying = self.dataSource[indexPath.row];
这段代码的时候,就能完成cell中各控件的赋值操作
二 cell高度完美封装术
根据TableView的特性,在加载一个cell的时候,会首先需要通过方法heightForRowAtIndexPath:(NSIndexPath *)indexPath
设置cell的高度,然后再通过cellForRowAtIndexPath:(NSIndexPath *)indexPath
设置cell的内容。那么,理想情况下:
1.利用单例创建一个cell,这个cell的作用是在
heightForRowAtIndexPath:(NSIndexPath *)indexPath
方法里反复调用,动态计算cell的高度
2.给cell创建一个
-setCellHeight:(NSArray)array
的方法,用于通过内容动态计算cell的高度
- (NSInteger)setCellHight:(MyFeedbackModel *)myFeedback{
//因为TextField是通过AutoLayout设置的,现在需要根据内容动态设置TextField的高度,那么首先需要设置其左右距离屏幕的边距。
self.descrptionsLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - 24;
self.descrptionsLabel.text = myFeedback.content;
//根据数据调整view的显示规则
if (myFeedback.pic_path == nil || [myFeedback.pic_path length] == 0) {
self.feedbackImageView.hidden = YES;
self.feedbackImageView.alpha = 0;
_noImageViewConstraint.priority = 700;
_haveImageViewConstraint.priority = 500;
}else{
self.feedbackImageView.hidden = NO;
self.feedbackImageView.alpha = 1;
_noImageViewConstraint.priority = 500;
_haveImageViewConstraint.priority = 700;
}
//设置view"需要刷新"和"刷新"属性。
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
//获取到动态高度
CGSize size = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
//返回的高度需要+1,这里是有道理的。
return size.height + 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//通过单例动态计算cell高度
static WQMyFeedbackTableViewCell *cell = nil;
if (cell == nil){
cell = [[[NSBundle mainBundle] loadNibNamed:@"WQMyFeedbackTableViewCell" owner:self options:nil]lastObject];
}
MyFeedbackModel *model = [_dataSource objectAtIndex:indexPath.row];
return [cell setCellHight:model];
}
如上,即完成了TableView使用过程中最需要解决的两个问题。理解以上内容,就可以很好的把握TableView和cell的使用了。