2012-03-07 23 views
10

我在我的應用中使用UITableViewController作爲表格,並且我添加了NSFetchedResultsController以提供要在表格中顯示的數據(設置爲self,因爲它是委託)。向NSFetchedResultsController管理的UITableView添加額外的行

但是我想添加一個獨特的單元格作爲表格的最後一個單元格,與NSFetchedResultsController的謂詞產生的項目無關,我希望這個單元格始終位於表格的底部。

我試圖簡單地添加1〜表視圖數據源這些方法:

- (NSUInteger)numberOfSectionsInTableView:(UITableView *)sender 
{ 
    return [[self.fetchedResultsController sections] count] + 1; 
} 
- (NSUInteger)tableView:(UITableView *)sender numberOfRowsInSection:(NSUInteger)section 
{ 
    return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects] + 1; 
} 

然後捕捉在正在像這樣產生的這種額外行(該表僅具有1個部分)的情況下:

- (UITableViewCell *)tableView:(UITableView *)sender 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (indexPath.row == [self.fetchedResultsController.fetchedObjects count]) { 
     //Generate the last cell in table. 
    } else { 
     //Generate the rest of the cells like normal. 
    } 
    return nil; //To keep the compiler happy. 
} 

這檢查是否索引是最後一個單元格,並適當地處理它。

但是我仍然得到以下運行時錯誤:

*** Terminating app due to uncaught exception 'NSRangeException', 
reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' 

任何想法是什麼引起的?還是有更好的方式來添加一個額外的行到由NSFetchedResultsController控制的表視圖?

回答

13

如果您按照文檔(更新等)中的說明實現所有數據源方法,則獲取的結果控制器與tableview緊密相關。它會變得非常混亂和哈克。

您的「額外的行」可能是表的頁腳視圖嗎?這將始終處於最底層。讓它看起來像一個細胞並不是太多工作,但從它的外觀來看,你希望它看起來不同於其他細胞。

+0

啊是的,這實際上是一個更好的實現方式,謝謝。 (很明顯,我對iOS編程還是很新的:-)) – 2012-03-07 15:46:09

+0

是的,它變得非常黑客。這個想法非常簡單...非常感謝! – Shingoo 2012-04-04 19:24:02

+0

但這看起來像它 - http://stackoverflow.com/questions/10965098/nsfetchedresultscontroller-prepend-a-row-or-section – 2014-01-31 23:12:55

2

鑑於表只有一個部分,這個代碼如下錯誤:

- (NSUInteger)numberOfSectionsInTableView:(UITableView *)sender 
{ 
    return [[self.fetchedResultsController sections] count] + 1; 
} 

我懷疑當實現代碼如下嘗試檢索第二部分你的崩潰出現; + 1應該被刪除。

使用來自讀取結果控制器的表可以做更復雜的事情(參見NSFetchedResultsController prepend a row or section),所以我確信這個簡單的例子可以工作。

+0

仍然tableView:cellForRowAtIndexPath:將被調用[[self.fetchedResultsController節] count]次。 – 2014-06-25 17:52:04

0

爲什麼不使用內置於UITableView的頁眉和頁腳視圖?

實施例:

UIView *customBottomView = [UIView alloc] init... //set up your View (what you called custom bottom cell

self.table.tableFooterView = customBottomView; //或者tableHeaderView

從技術上講,您正在添加一個視圖,該視圖顯示在添加到表格並由TableView奇妙處理的表格的下方(或上方)。對於用戶而言,無法確定這是(最後一個)單元還是僅僅是一個視圖。如果你打算使用像didSelectRowAtIndexPath這樣的方法,你只需要解決方法