【发布时间】:2020-07-27 10:21:05
【问题描述】:
我的 collectionView 单元格上有一个 longtapgesture。如果我在一个单元格上点击 0.3 秒,该单元格会出现绿色边框,并且 cell.isSelected 更改为 true。 问题是,当我滚动 collectionView 时,边框消失并且我选择的所有单元格都是错误的。
func setupLongTapGesture() {
let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
longPressGesture.minimumPressDuration = 0.3
longPressGesture.delegate = self
collectionView.addGestureRecognizer(longPressGesture)
}
@objc func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
if longPressGestureRecognizer.state == UIGestureRecognizer.State.began {
let touchPoint = longPressGestureRecognizer.location(in: self.collectionView)
if let indexPath = collectionView.indexPathForItem(at: touchPoint) {
let cell = collectionView.cellForItem(at: indexPath) as! DetailCollectionViewCell
if cell.isSelected == true {
cell.layer.borderColor = UIColor.clear.cgColor
cell.layer.borderWidth = 2
cell.layer.cornerRadius = 20
cell.isSelected = false
} else if cell.isSelected == false {
cell.layer.borderColor = UIColor.green.cgColor
cell.layer.borderWidth = 2
cell.layer.cornerRadius = 20
cell.isSelected = true
}
}
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let width = collectionView.frame.width / 2
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DetailCollectionViewCell", for: indexPath) as! DetailCollectionViewCell
cell.cellWidth = width
cell.roundedView.frame = CGRect(x: 0, y: 0, width: width - 5 , height: width - 5)
cell.layer.masksToBounds = false
cell.layer.shadowColor = UIColor.black.cgColor
cell.layer.shadowOpacity = 0.1
cell.layer.shadowRadius = 2
cell.layer.shadowOffset = CGSize.zero
print(indexPath.row, cell.isSelected)
if cell.isSelected != true {
cell.layer.borderColor = UIColor.clear.cgColor
} else {
cell.layer.borderColor = UIColor.green.cgColor
}
return cell
}
【问题讨论】:
标签: swift xcode uikit collectionview