您的位置:首页 > 产品设计 > UI/UE

几种设置UITableView的cell动态高度的方法

2014-08-26 17:32 441 查看
1.UITableView加载的顺序是先得到表的行的高度,也就是先调用heightForRowAtIndexPath方法,然后再调用cellForRowAtIndexPath,所以我们有两个办法实现自定义cell高度(解决不同section的不同行高问题)。

一:改变它的加载顺序,或者说白了就是计算好cell高度后,再次让它加载heightForRowAtIndexPath方法;

二:直接在heightForRowAtIndexPath计算,做判断,直接返回对应的高度。

以下是第一种方法的实例:

UITableView设置单元格的高度的方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

return 64;

}

下面介绍如何扩大当前单元格并且缩小其他单元格:

// Somewhere in your header:

NSIndexPath *selectedCellIndexPath;

// And in the implementation file:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

selectedCellIndexPath = indexPath;

// Forces the table view to call heightForRowAtIndexPath

[tableView reloadRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

// Note: Some operations like calling [tableView cellForRowAtIndexPath:indexPath]

// will call heightForRow and thus create a stack overflow

if(selectedCellIndexPath != nil && [selectedCellIndexPath compare:indexPath] == NSOrderedSame){

return 128;

}else{

return 64;

}

}

reloadRowsAtIndexPaths方法将重新调用heightForRowAtIndexPath使单元格改变高度。

reloadRowsAtIndexPaths是在3.0.存储NSIndexPath的原因是因为不可能在堆栈不溢出的情况下在 heightForRowAtIndexPath调用类方法例如cellForRowAtIndexPath 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: