swiftuicollectionviewuicollectionviewcell

change collection view cell background colour dynamically on button action not working


I try to change the background colour of specific cell on button action. Color of cell is changing but but I scrolling this collection view the color of cell misplace from there original position first time when I click on button to change the color

when I scrolling this collection view which contain question number, color position in this control misplaced like in this imagecolor position change after scrolling here and there

How I can handle this problem that collection view cell color never change their position automatically.

This is my code on button click to change the color :

let indexs = IndexPath(row: currentQuestion, section: 0)
let celi = questionNumberCollection.cellForItem(at: indexs)
celi?.backgroundColor = .blue

Solution

  • Problems is

    You are changing the background color of the cell but you're not maintaining the state of the cell anywhere in your model which is important in the case where the cell is reused while scrolling.

    Solution:

    A simple and standard solution might be maintaining a state variable in a model or as a separate array, and change the background color in the cellforRowatIndexPath method.

    Example:

    struct Question {
    
        var desc:String
        var mark:Int
        var status:AnsweringStatus
    }
    
    enum AnsweringStatus {
        case notAttented,correct,inCorrect
    }
    
    class ViewController:UIViewController,UICollectionViewDataSource {
    
        var dataSource:[Question]!
    
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return dataSource.count
        }
    
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ShowCell", for: indexPath) as! ShowCell
            switch dataSource[indexPath.row].status {
    
            case .notAttented:
                cell.backgroundColor = .gray
            case .correct:
                 cell.backgroundColor = .red
            case .inCorrect:
                 cell.backgroundColor = .green
            }
            return cell
        }
    
    }
    

    Have showcased only the parts necessary to solve the issue. So on click of the button just changing the state in the respective model object using the index path and reloading the collection view will do the job.

    Provide more insights about the issue, if this doesn't work for you.