heightForRowAtIndexPath之前调用cellForRowAtIndexPath
问题描述:
我试图减少重复的代码时,布置我的tableview,但运行到生命周期的问题。基本上它的heightFroRowAtIndexPath在cellForRowAtIndexPath之前被调用。这是应该发生的,我明白为什么。heightForRowAtIndexPath之前调用cellForRowAtIndexPath
但是......
我有一个是在故事板制定了一个小区。它有一个可选字段。如果可选字段不在数据中,则删除该字段的标签。但是我在自定义单元实现去除标签:
CustomCell(扩展的UITableViewCell)
- (void) configureCellForData: (Data *) data {
if (data.optional) {
self.optionalLabel.text = [data.optional];
} else {
[self.optionalLabel removeFromSuperview];
}
}
然后在的cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:self.tableLayout[indexPath.section][indexPath.row]];
[cell configureCellForData:self.data];
return cell;
}
伟大的工程设立的单元格。然而,如果可选字段被删除,高度是错误的,即如果可选字段被删除,我需要调整。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:self.tableLayout[indexPath.section][indexPath.row]];
CustomCell *headerCell = (CustomCell *) cell;
if (self.data.optional == nil) {
return cell.bounds.size.height - headerCell.optionalLabel.bounds.size.height;
}
return cell.bounds.size.height;
}
}
它似乎并不像很多,但我简化我的支票,以“data.optional ==无”,这是比这更复杂,涉及到DB调用。
有没有更好的方法来设置这样的话,我不需要在计算单元格高度和单元格初始化时一次检查两次?
答
如果您只想检查一次,您可以存储一组布尔值数组,用于存储数据是否存在或不存在。因此,请检查每行,将结果存储到数组中,然后再次检查,检查数组是否具有该单元格的值,如果有,则使用该值,如果不是,则使用该值数据库调用。
请确保您只将值存储在与indexPath关联的数组索引中,并且如果数组比您所处的indexPath更短,则需要进行调用并将该值添加到数组中。
编辑:当我仔细考虑它时,我会将bool值放在单元格本身上,然后只需拨打cell.isDataAvailable
(或任何您想要的值)以避免第二次调用设置单元格,就像你已经在heightForRowAtIndexPath中检查过了一样。
而不是手动计算行高,可以使用自动布局,并让单元格的内容确定高度? http://stackoverflow.com/q/18746929/3711928 –
这看起来很有前途,但无法实现。我仍然需要重写heightForRowAtIndexPath以在某些情况下返回0,我不希望单元格显示。好像当我重写heightForRowAtIndexPath我需要返回的东西作为自动高度不起作用。 – lostintranslation
同样在阅读完它后,它对于定义好的标签中的动态内容似乎很有效。当我从视图中删除标签时,不确定如何正确调整它的大小。 – lostintranslation