Xcode UICollectionViewCell选择多个单元格
我正在尝试制作一个应用程序来选择多个单元格,所以假设我们有9个单元格,索引范围从0到8 这就是我想做的Xcode UICollectionViewCell选择多个单元格,xcode,swift,Xcode,Swift,我正在尝试制作一个应用程序来选择多个单元格,所以假设我们有9个单元格,索引范围从0到8 这就是我想做的 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { var cell = collectionView.cellForItemAtIndexPath(indexPath) if cell?.selected == true {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var cell = collectionView.cellForItemAtIndexPath(indexPath)
if cell?.selected == true {
cell?.backgroundColor = UIColor.orangeColor()
}
}
并取消选择Func()
如果用户选择一个单元格->如果取消选择一个单元格->clearColor“白色”,这就足够简单了
是的,除了
如果用户选择单元格0,它也会更改单元格6的颜色,“请记住,单元格6没有被选中,只是更改了它的外观”。如果单元格1选择了单元格7更改等,则与此相同;如果我取消选择单元格0或单元格6,则两者都将更改
所以我尝试了cell?.selected==true
,UICollectionView.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()
第一组
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
}
测试您的代码,相同的行为:(,单击一个单元格更改另一个单元格的外观也需要使用此选项以避免重复
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
}