如何解决迅速滚动后didDeselectItemAt不起作用
我正在设计一个带有collectionview的菜单选项卡栏,我想在选择标签时更改标签的颜色。
一切正常,但是当所选项目不在屏幕上(由于滚动到屏幕之外)时,didDeselectItemAt内部的功能不再起作用。
反正有解决这个问题的方法吗?下面是代码:
func collectionView(_ collectionView: UICollectionView,didDeselectItemAt indexPath: IndexPath) {
if collectionView == self.productMenuCollectionView {
guard let cell = self.productMenuCollectionView.cellForItem(at: indexPath) as? ProductMenuCollectionViewCell else {
return
}
cell.label.textColor = UIColor.black
} else {
}
}
func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
if collectionView == self.productMenuCollectionView {
let cell = self.productMenuCollectionView.cellForItem(at: indexPath) as! ProductMenuCollectionViewCell
cell.label.textColor = CustomColor.primary
} else {
}
}
解决方法
您正在观察此行为,因为单元已被重用,因此一个单元可以用于一个索引路径,但是当该索引路径滚动到视图之外,而新的索引路径滚动到视图中时,可以使用同一单元对象用于其中一个新单元。每当您dequeue
某个单元格时,请记住,您可能正在重新配置旧单元格!
所以发生的是,一个旧的选定单元格移出了视野,并被重新配置以在新的索引路径上使用。您的代码可能当时会从该单元格中删除选定的颜色,因此当您向上滚动时,该颜色就消失了。
您应该做的是在ProductMenuCollectionViewCell
中覆盖isSelected
:
override var isSelected: Bool {
didSet {
if isSelected {
self.label.textColor = CustomColor.primary
} else {
self.label.textColor = UIColor.black
}
}
}
在cellForItemAtIndexPath
中:
if collectionView.indexPathsForSelectedItems?.contains(indexPath) ?? false {
cell.isSelected = true
} else {
cell.isSelected = false
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。