Установка градиентного фона в UIView в ячейке представления коллекции - PullRequest
0 голосов
/ 26 октября 2019

У меня есть UICollectionViewCell, который содержит UIView, на котором я хочу установить градиентный фон. Это мой cellForItemAt метод:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell: PaymentMethodCVCell = collectionView.dequeueReusableCell(withReuseIdentifier: "paymentMethodCVCell", for: indexPath) as? PaymentMethodCVCell {
           let row = indexPath.row
           cell.rewardsCard.setGradientBackground(colorTop: appRed, colorBottom: appRed.darkerColor(), withCornerRadius: 10)
           return cell
    }

    return UICollectionViewCell()
}

, где setGradientBackground определяется как расширение UIView:

func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius : CGFloat){
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
        gradientLayer.locations = [0, 1]
        gradientLayer.frame = bounds
        gradientLayer.cornerRadius = withCornerRadius
        layer.insertSublayer(gradientLayer, at: 0)
}

Это прекрасно работает, но только когда я прокручиваю вверхи вниз в UICollectionView и ячейки перезагружаются - ячейки, изначально загруженные на страницу, не имеют правильно установленного фона. Выполнение этого в самом UICollectionViewCell тоже не работает.

1 Ответ

1 голос
/ 26 октября 2019

Представление bounds еще не известно внутри cellForRowAt плюс оно добавит много градиентов при прокрутке, когда ячейки сняты с очереди

gradientLayer.frame = bounds

То есть внутри ячейки

var once = true

override func layoutSubviews() {
   super.layoutSubviews()
    if once {
        // add gradient
        once = false
    }
 } 

ИЛИ

override func layoutSubviews() {
   super.layoutSubviews()
    if !(rewardsCard.layer.sublayers?.first is CAGradientLayer ) {
        // add gradient 
    }
 } 
...