【发布时间】:2021-04-11 12:32:17
【问题描述】:
我有一个集合视图。我在集合视图单元格中有一个名为家具选择Btn 的按钮。
当我点击集合视图中的按钮时,它会将按钮图像设置为 selected.png。当我再次点击它时,它会被取消选择,我设置为 unselected.png 图像。 当我点击按钮时,cardselection 方法被触发,我将点击的索引保存在 allFurnituresArray 中。
现在,当我滚动此集合视图时,即使我没有选择它们,也很少有单元格被选中。这通常发生在视图之外的单元格上。我相信单元格会被重用。 例如,如果我选择了第一个按钮并开始滚动,我看到第四个按钮也处于选中状态
所以我尝试检查 cellforRow 方法是否针对已选择的 allFurnituresArray 索引,甚至这不起作用。 我还尝试查看是否可以使用 prepareForReuse() 但我们没有获得有关我滚动到那里的索引的信息。
有人可以帮忙
CardCollectionViewCell.swift
class CardCollectionViewCell: SwipingCarouselCollectionViewCell {
@IBOutlet weak var furnitureSelectionBtn: UIButton!
static let reuseIdentifier = "CardCollectionViewCell"
static var nib: UINib {
get {
return UINib(nibName: "CardCollectionViewCell", bundle: nil)
}
}
override func awakeFromNib() {
super.awakeFromNib()
furnitureSelectionBtn.setBackgroundImage(image, for: UIControl.State.normal)
}
CardViewController.swift
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CardCollectionViewCell.reuseIdentifier, for: indexPath) as! CardCollectionViewCell
// Configure the cell
cell.delegate = self
cell.furnitureSelectionBtn.tag = (indexPath as NSIndexPath).row
for element in allFurnituresArray {
print(element)
if (indexPath.row) == element as! Int {
let image1 = UIImage(named: "selected.png")
cell.furnitureSelectionBtn.setBackgroundImage(image1, for: UIControl.State.selected)
}
else
{
let image1 = UIImage(named: "unselected.png")
cell.furnitureSelectionBtn.setBackgroundImage(image1, for: UIControl.State.normal)
}
}
cell.furnitureSelectionBtn.addTarget(self, action: #selector(CardViewController.cardselection(_:)), for: .touchUpInside)
return cell
}
@objc func cardselection(_ sender:UIButton!)
{
if sender.isSelected == true {
sender.isSelected = false
let image1 = UIImage(named: "unselected.png")
sender.setBackgroundImage(image1, for: UIControl.State.normal)
allFurnituresArray.remove(sender.tag)
}else {
sender.isSelected = true
let image1 = UIImage(named: "selected.png")
allFurnituresArray.add(sender.tag)
sender.setBackgroundImage(image1, for: UIControl.State.selected)
}
print("Button tapped")
print(sender.tag)
}
【问题讨论】:
-
删除你的 for 循环并使用 if 条件和 allFurnituresArray.contains(element)。如果结果为真,则设置选定的图像,否则设置未选定的图像。
-
另外,如果你已经为按钮状态设置了图像,比如 'UIControl.State.selected',那么你只需要设置 isSelected = true/false 来更新图像
标签: ios swift uicollectionview reuseidentifier