如何解决无法在allowMultipleSelection上取消选择预选的uicollectionviewcells 讨论
我的收藏夹视图和多重选择遇到了一些问题。问题是当我预先选择它时,然后我无法取消选择它。我已经制作了一个示例项目,以便有人可以查看。我已经上传到我的github个人资料:https://github.com/ahhhv/CollectionViewSelection
但是如果有人已经知道答案了,我会在这里放一些代码。
// Cell
override public var isSelected: Bool {
didSet {
if isSelected {
layer.borderWidth = 1
layer.borderColor = UIColor.systemBlue.cgColor
titleLabel.textColor = .systemBlue
} else {
layer.borderWidth = 0
titleLabel.textColor = .black
}
titleLabel.accessibilityLabel = self.isSelected ? "\(selectedItemText) \(isSelectedText)" : selectedItemText
titleLabel.accessibilityTraits = UIAccessibilityTraits.button
}
}
// VC
public func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let item = item else { return UICollectionViewCell() }
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ModuleSelectorCell.reuseID,for: indexPath) as? ModuleSelectorCell {
cell.set(item: item.items[indexPath.item])
if item.selectionType == .exclusive {
if let selectedItem = item.selectedItems,let first = selectedItem.first {
if first == indexPath.item {
cell.isSelected = true
}
}
} else {
if let selectedItems = item.selectedItems {
selectedItems.forEach { num in
if num == indexPath.item {
cell.isSelected = true
}
}
}
}
return cell
}
return UICollectionViewCell()
}
我知道这是一个远景,但是我已经为此苦苦挣扎了很长时间了。
最亲切的问候
解决方法
在isSelected
内设置collectionView(_:cellForItemAt:)
的任何特定原因? Apple Documentation不建议这样做。
讨论
此属性仅管理单元格的选择状态。此属性的默认值为false,表示未选择状态。
通常,您不直接设置此属性的值。以编程方式更改此属性的值不会更改单元格的外观。选择单元格并使其突出显示的首选方法是使用集合视图对象的选择方法。
因此,我的建议是进行以下修改以解决您的问题。
您需要处理的唯一问题是-您无法避免在scrollPosition
中设置selectItem(at:animated:scrollPosition)
。我想如果所有预选项目都在您的收藏视图的顶部,那么通过.top
就不会成为一个问题。否则,您需要提出一个更好的策略。无论如何,您始终可以使用
collectionView.setContentOffset(.zero,animated: false)
定位collectionView
的contentOffset。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。