2013-04-22 63 views
0

我正在製作一個應用程序,用戶可以在詳細視圖中收藏不同的項目。在表格視圖中單獨顯示收藏夾

我有一個表格視圖,其中顯示所有項目,我想在同一個表格視圖的單獨部分中顯示最愛。任何想法如何做到這一點?

此時我將所有的收藏夾保存在一個名爲favouriteItems的NSMutableArray中。

我想我必須從原始數組中刪除最喜歡的對象。 但我可以用兩個數組填充tableview嗎? 一個陣列在第一部分中的最愛,其餘部分在第二部分

+0

所以你到目前爲止嘗試過什麼?你如何「知道」哪一個對象是最喜歡的?它是在兩個部分顯示兩個數組還是將一個數組分成兩個,這會阻止你? (不要回答「Both」) – 2013-04-22 08:45:19

回答

2

當然,你可以。你的表格視圖只需要2個部分。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 2; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    switch (section) { 
     case 0: 
      return normalItems.count; 
      break; 
     case 1: 
      return favouriteItems.count; 
     default: 
      break; 
    } 
    return 0; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    switch (section) { 
     case 0: 
      return @"Normal Items"; 
      break; 
     case 1: 
      return @"Favorite Items"; 
     default: 
      break; 
    } 
    return nil; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"MyCell"; 

    CeldaCell *cell = (CeldaCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[CeldaCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    switch (indexPath.section) { 
     case 0: 
      cell.textLabel.text = [normalItems objectAtIndex:indexPath.row]; 
      break; 
     case 1: 
         cell.textLabel.text = [favouriteItems objectAtIndex:indexPath.row]; 
      break; 
    } 

    return cell; 
} 
+0

感謝您的回答。我在我的應用程序中做了一些更改,現在我只有一個包含所有食譜的數組,並使用sortUsingComparator對它們進行排序,以便首先顯示收藏夾。我有一個稱爲Item的模型對象,它帶有一個名爲isFavourite的BOOL。我可以把所有的項目都放在一個部分中,而其他所有人都放在另一部分中? – Jojo 2013-04-23 08:00:51

+0

使用2個數組可能會更高效。但你也可以像你說的那樣去做。你只需要有2個部分,並計算通訊錄UITableViewDatasource方法中的收藏夾數量和收藏夾數量。我可以發佈一些代碼,但如果你嘗試然後再回來有任何疑問,會更好。 – Odrakir 2013-04-23 08:48:46

+0

我幾乎在那裏。當我添加一個最喜歡的時候,它會移動到右側部分,但是在原始部分它被一個空白單元格替換爲一個空白標籤,當我點擊該行時,我喜歡的項目的詳細視圖顯示出來。 在numberOfRowsInSection循環所有我的項目,並有兩個整數,如果item.isFavourite == 1增加。在cellForRowAtIndexPath我也檢查是否item.isFavourite = 1或0.我設置cell.textlabel = item.title在我的if語句。 – Jojo 2013-04-23 09:04:28