killvak
killvak

Reputation: 96

UICollectionViewCell, multiple cell size, set gradientView width not set to the current cell size and sometimes changes when scrolling

i have 2 sizes for the cells in this class and that got me in a alot of troubles since i have to set bottom gradientView to the cell. When i first open the viewController every thing is set right except sometimes the gradient view colors doesn't look the same in some cells, but the real problem begin when you start scrolling, the bottom gradient view cut in half in the big cells and the gradientColors got really missy as u see in the image below some has really dark color as the bottom color and some has yellowish color instead which make the cells don't look the same

How i setup the cell size :

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchProductsCell", for: indexPath) as! SearchProductsCell
    cell.configCell(data: data[indexPath.row])
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let smallCellSize : CGFloat =  self.collectionView.frame.height  / 2.11
    let height = indexPath.row % 3 == 0 ? self.collectionView.frame.height  : smallCellSize
     return CGSize(width: height, height: height)
}

and that's the cell class setup :

 class SearchProductsCell: UICollectionViewCell {

@IBOutlet weak var imageV: UIImageView!
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var gradientView: UIView!

var isGradientAdded = false

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func prepareForReuse() {
    super.prepareForReuse()
}


func configCell(data : Product_Data ) {

    let img = data.image == "" ? data.thumb : data.image
    imageV.setupApiImage(imagePath: img)
    titleLbl.text = data.name
    if isGradientAdded == false {
        addGradient()
        isGradientAdded = true
    }
}

func addGradient () {
    let gradient = CAGradientLayer()
    gradient.frame = self.bounds
    let topColor = UIColor.yellow
    let botomColor = UIColor.red
    gradient.colors = [topColor.cgColor, botomColor.cgColor]
    gradientView.layer.insertSublayer(gradient, at: 0)
} 

    }

enter image description here

Upvotes: 1

Views: 293

Answers (1)

vacawama
vacawama

Reputation: 154671

Because of cell reuse, your gradient frame will become out of date anytime the cell geometry changes.

In your SearchProductsCell class, update the frame of your gradient in an override of layoutSubviews:

override func layoutSubviews() {
    super.layoutSubviews()
    if isGradientAdded {
        gradientView.layer.sublayers?.first?.frame = self.bounds
    }
}

Upvotes: 2

Related Questions