У меня есть 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
тоже не работает.