Swift 4 - 如果已选择,请取消选择集合视图单元格
Posted
技术标签:
【中文标题】Swift 4 - 如果已选择,请取消选择集合视图单元格【英文标题】:Swift 4 - deselect collection view cell if already selected 【发布时间】:2018-02-05 17:54:16 【问题描述】:我有一个集合视图,用户可以在其中选择多个单元格并将索引数组发送到服务器以保存他们的选择。
一切正常,除了在创建集合视图时需要单击所选项目两次才能取消选择它们。
如何解决双击的问题?
extension ThirdViewController: UICollectionViewDelegate, UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return categoryList.count
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! UserCategoryCollectionViewCell
cell.categoryLbl.text = categoryList[indexPath.row]
if Defaults.hasKey(.categoryListIndices)
if (Defaults[.categoryListIndices]?.contains(indexPath.row))!
cell.alpha = 0.1
cell.isSelected = true
else
cell.alpha = 1
return cell
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
let cell = collectionView.cellForItem(at: indexPath) as! UserCategoryCollectionViewCell
cell.alpha = 0.1
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)
let deselectedCell = collectionView.cellForItem(at: indexPath) as? UserCategoryCollectionViewCell
deselectedCell?.alpha = 1
print(deselectedCell?.isSelected)
collectionView.deselectItem(at: indexPath, animated: false)
【问题讨论】:
您必须将UITapGestureRecognizer
和setNumberOfTapsRequired = 2
设置为单元格以进行双击事件。
【参考方案1】:
首先。将此添加到您的 viewDidLoad。
collectionView?.allowsMultipleSelection = true
然后添加这两个函数。
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
let cell=collectionView.cellForItem(at: indexPath)
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: [])
cell?.backgroundColor = Color.hexStringToUIColor(hex: "#F5A331")
let lbl = cell?.subviews[1] as! UILabel
lbl.textColor = Style.cellHighlightedColor
override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)
collectionView.deselectItem(at: indexPath, animated: true)
let cell=collectionView.cellForItem(at: indexPath)
collectionView.deselectItem(at: indexPath, animated: true)
cell?.backgroundColor = UIColor.white
let lbl = cell?.subviews[1] as! UILabel
lbl.textColor = UIColor.darkGray
这样就可以了
【讨论】:
以上是关于Swift 4 - 如果已选择,请取消选择集合视图单元格的主要内容,如果未能解决你的问题,请参考以下文章
UICollectionView 的不可见单元格未被取消选择 - Swift