我有一个带有两个自定义单元格的集合视图,一个用于网格,一个用于列表,我希望能够触摸单元格并选择它们,如果要删除或共享它们,我现在想要的只是能够选择和去除它们,生病后发布我的代码结果是当我触摸一个单元格时,所有单元格都被选中!这是代码:
{{1}}
答案 0 :(得分:10)
在PhotoCollectionCell
和cell2_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/highlighting
或delegate
中的实际dataSource
。
确保您的collectionView
将allowsSelection
属性设为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;
}
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