ios - Swift collectionView 选择单元格多选

标签 ios swift collectionview

我有一个包含 2 个部分的 UICollectionView。我想在用户点击单元格时选择它。

每次用户点击单元格时,我的代码都会正确运行,单元格变小并且其中出现一个复选标记(它是我添加为单元格 subview 的 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)                
    }
}

最佳答案

确保在 viewDidLoad() 或 Storyboard中将 collectionView 的多选属性设置为 true

 collectionView?.allowsMultipleSelection = true 

关于ios - Swift collectionView 选择单元格多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37097647/

相关文章:

ios - 不同动画 block 中的 CGAffineTransform 属性

ios - 输入图像=零: Filtered Image not displaying?

ios - Xcode plist 验证脚本

ios - 动画 UICollectionView 页脚高度

swift - 如何从另一个 UICollectionViewCell 更改标签的值

android - 在 .net 中实现从移动应用程序到服务器的同步

ios - 手势更新中的快速崩溃

swift - 无法在 IOS10 中锁定一个 View Controller 的旋转

c# - 如何在使用过滤器时获取 CollectionView 的真实计数?

android - 在游戏引擎之上构建音乐制作应用程序是否有意义?