Swift collectionView选择单元格多选

Mar*_*coc 0 collectionview ios swift

我有UICollectionView2个部分.我想在用户点击它时选择单元格.

每次用户点击单元格时,我的代码都会正确运行,单元格会变小,并且会在其中显示复选标记(imageView我将其添加为单元格的子视图).问题是如果我在第一部分点击一个单元格,它会在第二部分中选择另一个单元格.这很奇怪,因为我使用了indexPath.

这是我的代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    // handle tap events            

    let cell = collectionView.cellForItemAtIndexPath(indexPath)
    let centerCell = cell?.center

    if cell!.frame.size.width == cellWidth {
        cell?.frame.size.width = (cell?.frame.size.width)!/1.12
        cell?.frame.size.height = (cell?.frame.size.height)!/1.12
        cell?.center = centerCell!

        let imageView = UIImageView()
        imageView.image = MaterialIcon.check?.imageWithColor(MaterialColor.white)
        imageView.backgroundColor = MaterialColor.blue.accent2
        imageView.frame = CGRectMake(1, 1, 20, 20)
        imageView.layer.cornerRadius = imageView.frame.height/2
        imageView.clipsToBounds = true
        if indexPath.section == 0 {
            imageView.tag = indexPath.row+4000
        } else {
            imageView.tag = indexPath.row+5000
        }
        print("IMAGEVIEW TAG: ",imageView.tag)
        cell?.addSubview(imageView)                
    }
}
Run Code Online (Sandbox Code Playgroud)

Cja*_*jay 7

确保true在您的viewDidLoad()或故事板中将collectionView上的multiple selection属性设置为

 collectionView?.allowsMultipleSelection = true 
Run Code Online (Sandbox Code Playgroud)

  • 是的,这不是问题......问题在于其他细胞会选择 (2认同)