提问者:小点点

集合视图按钮背景图像在滚动上重复


我有一个集合视图,在集合视图单元格中有一个名为furnitureSelectionBtn的按钮。

当我点击集合视图中的按钮时,它将按钮图像设置为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)

           }

共1个答案

匿名用户

保存选择状态的最佳方法是将此数据添加到datasource数组中的项中,例如,

(1)数据源数组

var items = [Item]()

(2)Didselectem...

items[indexPath.row].isSelected = !(items[indexPath.row].isSelected)

并处理单元格中的选择状态。