iPhone 6 iOS13下CollectionView滚动时isSelected触发、选中单元格边框消失问题求助
解决方案:iPhone 6 iOS 13 CollectionView滚动时选中单元格边框消失问题
针对你遇到的iPhone 6 iOS 13独有的CollectionView滚动时选中单元格边框消失问题,以下是几个可落地的解决思路:
1. 完全自定义选中状态,不依赖系统isSelected属性
iOS 13在旧设备上的CollectionView可能存在选中状态异常重置的系统特性问题,直接绕过系统的isSelected,自己维护选中状态是最稳妥的方案:
- 给自定义CollectionViewCell添加一个自定义选中属性,在属性变化时处理边框样式
- 重写系统
setSelected方法为空实现,避免系统状态干扰 - 在CollectionView的选中/取消选中代理方法里更新自定义状态
示例代码:
class CustomCollectionCell: UICollectionViewCell { // 自定义选中状态属性 var isCustomSelected: Bool = false { didSet { layer.borderWidth = isCustomSelected ? 2.0 : 0 layer.borderColor = isCustomSelected ? UIColor.systemBlue.cgColor : UIColor.clear.cgColor // 其他选中样式逻辑可在这里补充 } } // 重写系统方法,忽略系统选中状态变更 override func setSelected(_ selected: Bool, animated: Bool) {} } // 在ViewController中维护选中状态 private var selectedIndexPath: IndexPath? func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 取消之前选中的单元格 if let prevIndex = selectedIndexPath, let prevCell = collectionView.cellForItem(at: prevIndex) as? CustomCollectionCell { prevCell.isCustomSelected = false } // 设置当前选中单元格 if let currentCell = collectionView.cellForItem(at: indexPath) as? CustomCollectionCell { currentCell.isCustomSelected = true selectedIndexPath = indexPath } } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? CustomCollectionCell { cell.isCustomSelected = false selectedIndexPath = nil } }
2. 修复单元格复用时的状态重置问题
滚动时单元格复用可能导致系统错误重置选中状态,在prepareForReuse中强制恢复正确的选中样式:
- 给Cell添加
indexPath属性,在cellForItemAt中赋值 - 在
prepareForReuse里根据ViewController保存的选中索引,重新设置边框样式
示例代码:
class CustomCollectionCell: UICollectionViewCell { var indexPath: IndexPath? override func prepareForReuse() { super.prepareForReuse() // 从ViewController获取选中状态,恢复样式 guard let vc = window?.rootViewController as? YourViewController, let currentIndex = indexPath else { return } let shouldHighlight = vc.selectedIndexPath == currentIndex layer.borderWidth = shouldHighlight ? 2.0 : 0 layer.borderColor = shouldHighlight ? UIColor.systemBlue.cgColor : UIColor.clear.cgColor } } // 在cellForItemAt中初始化时设置正确状态 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellID", for: indexPath) as! CustomCollectionCell cell.indexPath = indexPath let isSelected = selectedIndexPath == indexPath cell.isCustomSelected = isSelected // 或者直接设置边框 return cell }
3. 禁用延迟内容触摸
iOS 13的旧设备上,delaysContentTouches的默认行为可能导致触摸事件处理异常,尝试关闭该属性:
collectionView.delaysContentTouches = false
以上方案中,第一种彻底脱离系统选中状态的方案最适合解决这类系统版本独有的兼容性问题,建议优先尝试。
内容的提问来源于stack exchange,提问作者Uladzislau Yakubovsky
相关产品推荐
相关产品推荐

