CollectionView多个单元格选择

时间:2016-09-18 14:05:26

标签: ios arrays swift uicollectionview

我有一个带有两个自定义单元格的集合视图,一个用于网格,一个用于列表,我希望能够触摸单元格并选择它们,如果要删除或共享它们,我现在想要的只是能够选择和去除它们,生病后发布我的代码结果是当我触摸一个单元格时,所有单元格都被选中!这是代码:

{{1}}

2 个答案:

答案 0 :(得分:10)

PhotoCollectionCellcell2_Class(或在公共superclass中),只需覆盖此方法

- (void) setSelected:(BOOL)selected 
{ 
     if (selected) 
     {        
         self.layer.borderColor = UIColor.blueColor().CGColor
         self.layer.borderWidth = 3
     } 
     else 
     {
         self.layer.borderColor = UIColor.clearColor().CGColor
     }
}

然后,您不必处理selection/highlightingdelegate中的实际dataSource

确保您的collectionViewallowsSelection属性设为YES

如果您需要multiple selection,请将allowsMultipleSelection设置为YES,并在delegate

中实施以下方法
- (BOOL) collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView.indexPathsForSelectedItems containsObject: indexPath])
    {
        [collectionView deselectItemAtIndexPath: indexPath animated: YES];
        return NO;            
    }
    return YES;
}

Swift Solution

collectionViewCell

的子类
override var selected: Bool {
    didSet {
        self.layer.borderWidth = 3.0
        self.layer.borderColor = selected ? UIColor.blueColor().CGColor : UIColor.clearColor().CGColor
    }
}
UICollectionViewDelegate中的

func collectionView(collectionView: UICollectionView, shouldSelectItemAt indexPath: NSIndexPath) -> Bool {
    if let selectedItems = collectionView.indexPathsForSelectedItems() {
        if selectedItems.contains(indexPath) {
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            return false
        }
    }
    return true
}

答案 1 :(得分:1)

基于Aerows解决方案 Swift 4.2

collectionViewCell的子类

override var isSelected: Bool {
        didSet {
            self.layer.borderWidth = 3.0
            self.layer.borderColor = isSelected ? UIColor.blue.cgColor : UIColor.clear.cgColor
        }
    }

UICollectionViewDelegate

func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
    if let selectedItems = collectionView.indexPathsForSelectedItems {
        if selectedItems.contains(indexPath) {
            collectionView.deselectItem(at: indexPath, animated: true)
            return false
        }
    }
    return true
}

非常重要,在您的viewDidLoad()上,不要忘记允许您的收藏夹查看多项选择

collectionView.allowsMultipleSelection = true

Apple documentation - allowsMultipleSelection