2014-04-23 32 views
2

我有一個UITableViewNSArray獲取其數據。該數組包含模型對象。我已將UITableView分成幾部分。現在我試圖讓一些部分可以多選,其他部分只能單選。我的模型對象有一個屬性,我用它來確定是否需要多選或單選。我快到了 - 我已經設法在正確的部分中進行多選和單選。下面是代碼:分組的UITableView - 允許多選和單選

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    self.selectedIndexPath = indexPath; 
    BBFilterProductAttribute *productAttribute = self.productAttributes[indexPath.section]; 

    if ([productAttribute.filterType isEqualToString:@"MULTI_SELECT_LIST"]) { 
     if (productAttribute.option[indexPath.row]) { 
      [self.selectedRows addObject:indexPath]; 
     } 
     else { 
      [self.selectedRows removeObject:indexPath]; 
     } 
    } 

    [self.tableView reloadData]; 
} 

爲了解決這個問題,再利用,當一些細胞有一個對勾,即使他們沒有選擇我在cellForForAtIndexPath:方法做到這一點:

if([self.selectedRows containsObject:indexPath]) { 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
} 

//For single selection 
else if (self.selectedIndexPath.row == indexPath.row && 
     self.selectedIndexPath.section == indexPath.section) { 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
} else { 
    cell.accessoryType = UITableViewCellAccessoryNone; 
} 

我的選擇每節都在按照他們的要求工作。每個部分允許多選或單選 - 取決於didSelectRowAtIndexPath:方法中的if語句。

的問題是:

如果我選擇在第2行,讓我們說這是一個選擇,然後我選擇在第3行,還單項選擇,從第2複選標記移動到節3.

我需要第2節和第3節保持單一選擇 - 但允許同時選擇一行。因此,它應該是這樣的:

  • 第1部分:(多選):選擇所有行
  • 第2部分:(單選):選擇
  • 第3節一排:(單選):一行選擇

取而代之的是,當我從第2條選擇一排,它看起來像這樣:

  • 第1節:(多選擇):所有行選擇
  • 第2部分:(單選:上一頁選擇刪除
  • 第3部分:(單選):選擇

回答

2

更改didSelectRowAtIndexPath:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    self.selectedIndexPath = indexPath; 
    BBFilterProductAttribute *productAttribute = self.productAttributes[indexPath.section]; 

    if ([productAttribute.filterType isEqualToString:@"MULTI_SELECT_LIST"]) 
    { 
     if (productAttribute.option[indexPath.row]) 
     { 
      [self.selectedRows addObject:indexPath]; 
     } 
     else 
     { 
      [self.selectedRows removeObject:indexPath]; 
     } 
    } 
    else 
    { 
     //Section is SINGLE_SELECTION 
     //Checking self.selectedRows have element with this section, i.e. any row from this section already selected or not 
     NSPredicate *predicate = [NSPredicate predicatewithFormat:@"section = %d", indexPath.section]; 
     NSArray *filteredArray = [self.selectedRows filteredArrayUsingPredicate:predicate]; 
     if ([filteredArray count] > 0) 
     { 
      //A row from this section selected previously, so remove that row 
      [self.selectedRows removeObject:[filteredArray objectAtIndex:0]]; 
     } 

     //Add current selected row to selected array 
     [self.selectedRows addObject:indexPath]; 
    } 

    [self.tableView reloadData];  
} 
+0

老兄你搖滾一行!完善。看來我需要進一步研究NSPredicate。永遠不會想到它! :) – Tander

+0

@Tander很高興知道它適合你。乾杯。 – Akhilrajtr

相關問題