Swift cell.isSelected与aspected不一样
我的collectionView手机上有一个长拍手势。如果我在单元格上点击0.3秒,该单元格将显示绿色边框,cell.isSelected将变为true。 问题是,当我滚动collectionView时,边框消失,我选择的所有单元格都为falseSwift cell.isSelected与aspected不一样,swift,xcode,uikit,collectionview,Swift,Xcode,Uikit,Collectionview,我的collectionView手机上有一个长拍手势。如果我在单元格上点击0.3秒,该单元格将显示绿色边框,cell.isSelected将变为true。 问题是,当我滚动collectionView时,边框消失,我选择的所有单元格都为false func setupLongTapGesture() { let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(targ
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
}
重复使用单元格您需要在模型中保留该数据(
cell.isSelected
selection状态)
if cell.isSelected != true {
cell.layer.borderColor = UIColor.clear.cgColor
} else {
cell.layer.borderColor = UIColor.green.cgColor
}
因此,我需要一个数组来存储其中选定的单元格?无论是否选择此索引,您都需要一个布尔数组……。是否可以使用indexPath.row来执行此操作?是的,您可以拥有选定的indexPath数组(如果1节为Int数组),并检查它是否在
cellForRowAt
中根据值着色