2013-03-12 83 views
2

我想知道如何設置我的UICollectionView,以便每節最多可以選擇1個單元格。我看到有用於UICollectionView的allowsMultipleSelection屬性,但我想知道如何防止在同一節中選擇多個單元。iOS UICollectionView單元格選擇每節

我是否需要在– collectionView:shouldSelectItemAtIndexPath:collectionView:shouldDeselectItemAtIndexPath:方法中實現邏輯,還是有更簡單的方法?

謝謝!

回答

8

在您的didSelectRowAtIndexPath方法,你可以做這樣的事情:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    NSArray * selectedRows = self.tableView.indexPathsForSelectedRows; 

    for (NSIndexPath * selectedRow in selectedRows) { 
     if ((selectedRow.section == indexPath.section) && (selectedRow.row != indexPath.row)) { 
      [self.tableView deselectRowAtIndexPath:selectedRow animated:NO]; 
     } 
    } 
} 

allowsMultipleSelection應設置爲YES。

希望它有幫助!

+1

感謝您的幫助。我不得不添加一條線,雖然... if(selectedRow.row!= indexPath.row)[collectionView deselectItemAtIndexPath:selectedRow animated:NO]; – 2013-03-13 01:21:20

+0

我繼續並編輯了包含該答案的答案。我完全錯過了! 謝謝! – Pablo 2013-03-13 13:52:32

+1

+1但是,這個答案談到了UITableView。儘管對於那些熟悉Cocoa的人來說,它仍然是一個有用的答案,但如果它提到UICollectionView,它會更好,因爲問題會特別提到UICollectionView。 – gavdotnet 2013-10-28 07:44:57

0

您可能需要在-shouldSelect-shouldDeselect中執行邏輯。也許保留一個字典中選擇的每個部分的細胞數

NSMutableDictionary *dict; 

- (BOOL)collectionView:(UICollectionView *)view shouldSelectItemAtIndexPath:(NSIndexPath *)path 
{ 
    NSInteger *section = path.section; 
    if (!dict) 
    { 
     dict = [[NSMutableDictionary alloc] init]; 
    } 
    NSNumber *numberSelected = [dict objectForKey:[NSNumber numberWithInteger:section]]; 
    if (numberSelected > 0) 
    { 
     return NO; 
    } 
    else 
    { 
     [dict setObject:[NSNumber numberWithDouble:numberSelected.doubleValue - 1] forKey:[NSNumber numberWithInteger:section]]; 
     return YES; 
    } 
} 
- (BOOL)collectionView:(UICollectionView *)view shouldDeselectItemAtIndexPath:(NSIndexPath *)path 
{ 
    NSInteger *section = path.section; 
    if (!dict) 
    { 
     dict = [[NSMutableDictionary alloc] init]; 
    } 
    NSNumber *numberSelected = [dict objectForKey:[NSNumber numberWithInteger:section]]; 

    numberSelected = [NSNumber numberWithDouble:numberSelected.doubleValue - 1]; 

    [dict setObject:numberSelected forKey:[NSNumber numberWithInteger:section]]; 

    return YES; 
} 

這應該工作。

0

在雨燕2.0:

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.collectionView.allowsMultipleSelection = true 
} 

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

    let selectedRows: [NSIndexPath] = self.collectionView.indexPathsForSelectedItems()! 
    for selectedRow: NSIndexPath in selectedRows { 
     if (selectedRow.section == indexPath.section) && (selectedRow.row != indexPath.row) { 
      self.collectionView.deselectItemAtIndexPath(selectedRow, animated: false) 
     } 
    } 
}