gpt4 book ai didi

xcode - UICollectionViewCell 快速选择多个单元格

转载 作者:搜寻专家 更新时间:2023-11-01 05:58:39 25 4
gpt4 key购买 nike

我正在尝试制作一个应用程序来选择多个单元格,所以假设我们有 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 这两个属性对我都不起作用。

我做错了什么吗?
这是与细胞重用有关的问题吗?如果可以,您能解释一下这种行为吗?

最佳答案

这样做:

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()

关于xcode - UICollectionViewCell 快速选择多个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31107856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com