我有一个包含 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/