Gradient in UIView inside UITableViewCell(collectionViewCell) changed after scroll Swift || Create GradientLayer on your tableViewCell(collectionViewCell) Swift

Gradient in UIView inside UITableViewCell changed after scroll 


Swift Collection View Cell changes gradient Color after scrolling
This is the tested  code and working fine for my end.

Add GradientLayer on the View.
Create UIView extension for adding gradient layer.

extension UIView {
    func setGradientBackground(colorOne: UIColor, colorTwo: UIColor, bounds_object: UIView){
        
        if let gradientLayer = layer.sublayers?.first as? CAGradientLayer {
            gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
        } else {
            let gradientLayer = CAGradientLayer()
            gradientLayer.frame = bounds_object.bounds
            gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
            gradientLayer.locations = [0.0, 1.0]
            gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
            gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
            layer.insertSublayer(gradientLayer, at: 0)
        }
    }
}

Add it from cellForRowAt

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withIdentifier: "yourCellId", for: indexPath) as? MyCell {
        cell.configureCell(content: data[indexPath.row])
    }
    return UICollectionViewCell()
}

Handle gradientLayer from configureCell(content

class MyCell: UICollectionViewCell {
@IBOutlet weak var gradientView: UIView! override func awakeFromNib() { super.awakeFromNib() } func configureCell(content: data) { gradientView.setGradientBackground(colorOne: UIColor(hexString: data?.gradient?.first ?? ""), colorTwo: UIColor(hexString: data?.gradient?.last ?? "").withAlphaComponent(0.38), bounds_object: gradientView) } }



Post a Comment

0 Comments