UICollectionViewCell快速选择多个单元格

时间:2015-06-29 04:34:38

标签: xcode swift

我试图让应用程序选择多个单元格,所以让我们假设我们有9个单元格从0到8进行索引。

这是我想要做的......

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

var cell = collectionView.cellForItemAtIndexPath(indexPath)

   if cell?.selected == true {
    cell?.backgroundColor = UIColor.orangeColor()
   }

}

取消选择Func()

    func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {        
       var cell = collectionView.cellForItemAtIndexPath(indexPath)
        cell?.backgroundColor = UIColor.clearColor()
    }

如果用户选择一个单元格,那么它很简单 - >如果取消选择单元格,则为橙色 - > clearColor' white' 所以这个代码正在工作,除了

如果用户选择单元格0,它也会更改单元格6的颜色,"请记住单元格6未被选中它只是改变它的外观"。如果单元格1选择了单元格7更改等,则单元格1也相同,如果我取消选择单元格0或单元格6两个更改。

所以我尝试了cell?.selected == trueUICollectionView.allowsMultipleSelection = true两个属性都不适合我。

我做错了什么?
这是与Cell Reuse有关的问题吗?如果是这样你能解释这种行为吗?

2 个答案:

答案 0 :(得分:5)

这样做:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
{
         var cell = collectionView.cellForItemAtIndexPath(indexPath)
         if cell?.selected == true {
            cell?.backgroundColor = UIColor.orangeColor()
         }
          else 
             cell?.backgroundColor = UIColor.clearColor()
}

还为UICollectionViewCell创建自定义单元格。同时更改cellForItemAtIndexPath功能:

if cell?.selected == true 
      cell?.backgroundColor = UIColor.orangeColor()
    else 
       cell?.backgroundColor = UIColor.clearColor()

答案 1 :(得分:1)

第一组collectionView.allowsMultipleSelection

然后例如点击更改边框:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let selectedCell : UICollectionViewCell = collectionView.cellForItem(at: indexPath)!

    selectedCell.layer.borderWidth = 2

}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let unselectedCell : UICollectionViewCell = collectionView.cellForItem(at: indexPath)!

    unselectedCell.layer.borderWidth = 0
}
相关问题