Ios 在集合视图单元格中的UIView上设置渐变背景
我有一个Ios 在集合视图单元格中的UIView上设置渐变背景,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,我有一个UICollectionViewCell,其中包含一个UIView,我想在其上设置渐变背景。这是我的cellForItemAt方法: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell: PaymentMethodCVCell = collectionView.dequ
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
中执行此操作本身也不起作用 在cellForRowAt
中还不知道视图bounds
,另外,当您滚动单元格时,它会添加许多渐变
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
}
}