【问题标题】:uibutton in collectionview cell action duplicatingcollectionview单元格动作复制中的uibutton
【发布时间】:2018-12-31 17:43:13
【问题描述】:

所以基本上我的问题是,当我单击集合视图单元格中存在的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
}

【问题讨论】:

  • 不要使用btn,而是将其替换为sender,并将发件人类型Any更改为UIButton并检查。
  • @AlishaChaudhary 你能贴出符合UICollectionViewDataSource 协议的代码吗?
  • 它仍然无法正常工作。在按下一个按钮时,两个按钮被按下。(0-5),(1-6),(2,7),(3-8),(4-9)

标签: ios swift uicollectionview uibutton


【解决方案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 中实现它以更新值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多