简体   繁体   中英

uibutton in collectionview cell action duplicating

So basically my problem is that when I click on a button which is present in collection view cell it should change the colour of button background colour. but the problem is it is changing the colour of another button. eg if I click on button 1 it changes the colour of button 6 automatically.

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
}

The problem is that the UICollectionView re-uses cell for optimized scroll performance. Hence it re-uses the cell at index 1 when displaying cell at index 6 for eg Therefore you need to set the state of the cell when ever it is updated/reused.

The following function is called everytime. So you need to set cell.btn. backgroundColor over here.

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

     ...
     return cell
}

Now, it is upto your individual implementation, how you want to update the model when selection is changed. One option is you can define a protocol and implement it in your ViewController to update the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM