我試圖減少重複的代碼時,佈置我的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調用。
有沒有更好的方法來設置這樣的話,我不需要在計算單元格高度和單元格初始化時一次檢查兩次?
而不是手動計算行高,可以使用自動佈局,並讓單元格的內容確定高度? http://stackoverflow.com/q/18746929/3711928 –
這看起來很有前途,但無法實現。我仍然需要重寫heightForRowAtIndexPath以在某些情況下返回0,我不希望單元格顯示。好像當我重寫heightForRowAtIndexPath我需要返回的東西作爲自動高度不起作用。 – lostintranslation
同樣在閱讀完它後,它對於定義好的標籤中的動態內容似乎很有效。當我從視圖中刪除標籤時,不確定如何正確調整它的大小。 – lostintranslation