我正在尝试创建一个应用程序来选择多个单元格,所以让我们假设我们有9个单元格从0到8的索引.
这是我想要做的......
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var cell = collectionView.cellForItemAtIndexPath(indexPath)
if cell?.selected == true {
cell?.backgroundColor = UIColor.orangeColor()
}
}
Run Code Online (Sandbox Code Playgroud)
并取消选择Func()
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
var cell = collectionView.cellForItemAtIndexPath(indexPath)
cell?.backgroundColor = UIColor.clearColor()
}
Run Code Online (Sandbox Code Playgroud)
如果用户选择一个单元格就足够了 - >如果取消选择单元格则为> orange - > clearColor'white'所以这个代码工作正常
如果用户选择单元格0,它也会更改单元格6的颜色,"请记住,单元格6未被选中,只需更改它的外观".对于单元格1,如果它选择了单元格7更改等等,同样如果我取消选择单元格0或单元格6两个更改.
所以我试过cell?.selected == true,UICollectionView.allowsMultipleSelection = true这两个属性都不适合我.
难道我做错了什么 ?
这是与Cell Reuse有关的问题吗?如果是这样你能解释这种行为吗?
做这个 :
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()
}
Run Code Online (Sandbox Code Playgroud)
还为UICollectionViewCell创建自定义单元格.还要改变你的cellForItemAtIndexPath功能:
if cell?.selected == true
cell?.backgroundColor = UIColor.orangeColor()
else
cell?.backgroundColor = UIColor.clearColor()
Run Code Online (Sandbox Code Playgroud)
第一套 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8616 次 |
| 最近记录: |