Swift CollectionView 取消选择不起作用
Posted
技术标签:
【中文标题】Swift CollectionView 取消选择不起作用【英文标题】:Swift CollectionView Deselection not working 【发布时间】:2017-11-20 07:30:15 【问题描述】:我正在使用自定义 UICollectionViewFlowLayout 类来实现滚动视图的多滚动行为。没有问题。 但是要进行自定义选择和取消选择,我需要在 shouldSelectItemAt 函数中使用自定义代码来正确选择/取消选择。 这是它的代码:
MyCustomCollectionViewController 内部:
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool
if(collectionView == customContentCollectionView)
let cell:MyContentCell = collectionView.cellForItem(at: indexPath)! as! MyCollectionViewController.MyContentCell
if(self.bubbleArray[indexPath.section][indexPath.item].umid != "")
// DESELECTION LOGIC
if(previouslySelectedIndex != nil)
let (bubbleBorder, bubbleFill) = getBubbleColor(selected: false)
// following line is error prone (executes but may or may not fetch the cell, sometimes deselect sometimes doesn't)
let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell
prevCell?.shapeLayer.strokeColor = bubbleBorder.cgColor
prevCell?.shapeLayer.fillColor = bubbleFill.cgColor
prevCell?.shapeLayer.shadowOpacity = 0.0
prevCell?.labelCount.textColor = bubbleBorder
previouslySelectedIndex = []
previouslySelectedIndex = indexPath
// SELECTION LOGIC
if(self.bubbleArray[indexPath.section][indexPath.item].interactions != "")
let (bubbleBorder, bubbleFill) = getBubbleColor(selected: true)
cell.shapeLayer.strokeColor = bubbleBorder.cgColor
cell.shapeLayer.fillColor = bubbleFill.cgColor
cell.shapeLayer.shadowOffset = CGSize(width: 0, height: 2)
cell.shapeLayer.shadowOpacity = 8
cell.shapeLayer.shadowRadius = 2.0
cell.labelCount.textColor = UIColor.white
return false
return true
MyContentCell 的代码:
class MyContentCell: UICollectionViewCell // CODE TO CREATE CUSTOM CELLS
var gradient = CAGradientLayer()
var shapeLayer = CAShapeLayer()
var horizontalLine = UIView()
var verticalLeftLine = UIView()
required init(coder aDecoder: NSCoder)
super.init(coder: aDecoder)!
setup()
override init(frame: CGRect)
super.init(frame: frame)
setup()
let labelCount: UILabel =
let myLabel = UILabel()
return myLabel
()
func setup() // initializing cell components here as well as later in cellForItemAt method
............
override func prepareForReuse()
self.shapeLayer.fillColor = UIColor.white.cgColor
self.shapeLayer.shadowOpacity = 0.0
问题可能是,当一个单元格被选中并且刚刚拖出屏幕时,它可能不会被破坏,这就是为什么准备重用功能没有跟踪它以进行取消选择。那么请告诉我如何取消选择刚刚离开屏幕的单元格(可见索引)?
【问题讨论】:
CollectionView?.collectionViewLayout.invalidateLayout() 【参考方案1】:你需要使布局无效
collectionView?.collectionViewLayout.invalidateLayout()
【讨论】:
它在里面没有工作应该选择方法。我应该把这段代码放在哪里?以上是关于Swift CollectionView 取消选择不起作用的主要内容,如果未能解决你的问题,请参考以下文章
UICollectionView 的不可见单元格未被取消选择 - Swift
Swift 3 - CollectionView 选择不可见
为啥当我向下滚动iOS(tableView内的collectionview)时取消选择单元格?