2015-10-05 37 views
0

我試圖減少重複的代碼時,佈置我的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調用。

有沒有更好的方法來設置這樣的話,我不需要在計算單元格高度和單元格初始化時一次檢查兩次?

+0

而不是手動計算行高,可以使用自動佈局,並讓單元格的內容確定高度? http://stackoverflow.com/q/18746929/3711928 –

+0

這看起來很有前途,但無法實現。我仍然需要重寫heightForRowAtIndexPath以在某些情況下返回0,我不希望單元格顯示。好像當我重寫heightForRowAtIndexPath我需要返回的東西作爲自動高度不起作用。 – lostintranslation

+0

同樣在閱讀完它後,它對於定義好的標籤中的動態內容似乎很有效。當我從視圖中刪除標籤時,不確定如何正確調整它的大小。 – lostintranslation

回答

0

如果您只想檢查一次,您可以存儲一組布爾值數組,用於存儲數據是否存在或不存在。因此,請檢查每行,將結果存儲到數組中,然後再次檢查,檢查數組是否具有該單元格的值,如果有,則使用該值,如果不是,則使用該值數據庫調用。

請確保您只將值存儲在與indexPath關聯的數組索引中,並且如果數組比您所處的indexPath更短,則需要進行調用並將該值添加到數組中。

編輯:當我仔細考慮它時,我會將bool值放在單元格本身上,然後只需撥打cell.isDataAvailable(或任何您想要的值)以避免第二次調用設置單元格,就像你已經在heightForRowAtIndexPath中檢查過了一樣。

相關問題