这里要涉及到tableview 的两个方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 和
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
我们要清楚这两个方法的调用顺序,先heightForRowAtIndexPath然后是cellForRowAtIndexPath
//动态获取cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"HomeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
//设置cell数据
return cell;
}
注意一点,本人使用多次,发现最好把初始化的控件都封装到cell里面,避免初始化控件在cell里,否则会出现很多问题,如果觉得封装不了,只能手动设置每个cell的高度。