首页 文章

集合视图中的uibutton单元格动作重复

提问于
浏览
0

所以基本上我的问题是,当我点击集合视图单元格中的 button 时,它应该改变按钮背景颜色的颜色 . 但问题是它正在改变另一个按钮的颜色 . 例如,如果我点击按钮1,它会自动改变按钮6的颜色 .

class hello: UICollectionViewCell {

    @IBOutlet weak var btn: UIButton!

    @IBAction func click(_ sender: Any) {

        if btn.isSelected == true
        {
            btn.backgroundColor = UIColor.red
            btn.isSelected = false
        }
        else{ btn.backgroundColor = UIColor.purple
            btn.isSelected = true
        }
    }

    override func prepareForReuse() {
        super.prepareForReuse()
    }
}
          view controller file

func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "happy", for: indexPath) as! hello

    if cell.btn.isSelected
    {
        cell.btn.backgroundColor = UIColor.red
                }
    else{ cell.btn.backgroundColor = UIColor.purple

    }

    cell.btn.tag = indexPath.item
    print(cell.btn.isSelected ,indexPath.row)
    return cell
}

1 回答

  • 1

    问题是UICollectionView重新使用单元格来优化滚动性能 . 因此,当在索引6处显示单元格时,它重新使用索引1处的单元格 . 因此,您需要在更新/重用时设置单元的状态 .

    每次调用以下函数 . 所以你需要设置cell.btn . backgroundColor在这里 .

    func collectionView(_ collectionView: UICollectionView, cellForItemAt 
    indexPath: IndexPath) -> UICollectionViewCell {
         ...
         ...
         if dataSource[indexPath.row].selected {
           btn.backgroundColor = UIColor.red 
         }else {
           btn.backgroundColor = UIColor.purple
         }
    
         ...
         return cell
    }
    

    现在,这取决于您的个人实现,在更改选择时您希望如何更新模型 . 一种选择是您可以定义协议并在ViewController中实现它以更新值 .

相关问题