2013-04-10 65 views
3

我已經看過很多關於如何通過覆蓋heightForRowAtIndexPath來隱藏靜態UITableViewCell的示例,雖然我現在已經運行了,但是看起來如此麻煩以至於我想看看我是否做錯了什麼。只能通過覆蓋heightForRowAtIndexPath來更改靜態UITableViewCell的高度?

我有一個UITableViewController與約8行的表視圖。我的應用程序中的這個屏幕顯示了一個對象,例如,一行是描述,一個是圖像,一個是地圖視圖等。所有行都是靜態的。

在某些情況下,顯示的某些對象沒有地圖,所以我想隱藏包含mapview的行。由於它是一個靜態行,我一直在考慮通過爲該行設置一個outlet屬性(例如@property (weak, nonatomic) IBOutlet UITableViewCell *mapViewRow;),然後我可以以某種方式將該行的高度設置爲0或隱藏viewDidLoadviewWillAppear中的該行。但是,似乎唯一的方法是重寫heightForRowAtIndexPath方法,這很麻煩,因爲我需要在代碼中硬編碼地圖行的索引,例如,

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.row == 6 && self.displayItem.shouldHideMap) { 
     return 0; 
    } 
    return [super tableView:tableView heightForRowAtIndexPath:indexPath]; 
} 

當然,並不是什麼大不了的事,但只是在一個tableview上漿靜態行全路好像它違背了擺在首位將它們設置在故事板的點。

+0

你有靜態tableView靜態行,所以硬編碼索引應該沒問題。我使用枚舉,它隱藏絕對數字。 – JOM 2015-06-17 10:03:10

回答

2

編輯 - 理我的回答

後面要更改的行必須重新加載或者整個表或包含該行的一個子集的高度。 B/c在表中有一行有零點高度有點奇怪,我更喜歡修改你的數據源,使表中不存在該行。

有很多方法可以做到這一點。您可以從displayItem構建一個數組,其中數組中的每一行都對應於表中具有適當數據的行。你會重建這個數組,然後調用[tableView reloadData]。我的原始答案也可以通過將每個數據元素視爲0或1行的部分來消除不需要的行。

原來的答案

是您的tableview一個普通的或分組的風格?如果它是普通樣式,則可以將每行視爲一個其中包含0或1行的部分。在你的tableView數據源和委託方法中,你可以使用section索引來標識你關心該部分的self.displayItem中的數據。

您的代碼將是這樣的:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 8; // max number of possible rows in table 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    NSInteger rows = 1; 

    // set self.mapSectionIndex during initialization or hard code it 
    if (section == self.mapSectionIndex && self.displayItem.shouldHideMap) { 
     rows = 0; 
    } 
    return rows; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:indexPath 
{ 
    return 60.0f; // whatever you want the height to be 
} 

// also modify tableView:cellForRowAtIndexPath: and any other tableView delegate and dataSource methods appropriately 
0

您可以覆蓋heightForRowAtIndexPath,只是在它return UITableViewAutomaticDimension;寫這將使電池自動計算高度UILabel高度> =。它爲我工作。