ios - UICollectionViewCell,多个单元格大小,设置 gradientView 宽度未设置为当前单元格大小,滚动时有时会发生变化

标签 ios swift swift3 uicollectionview uicollectionviewcell

我在这个类中有 2 种尺寸的单元格,这让我遇到了很多麻烦,因为我必须将底部 gradientView 设置为单元格。 当我第一次打开 viewController 时,一切都设置正确,除了有时渐变 View 颜色在某些单元格中看起来不一样,但真正的问题是当你开始滚动时,底部渐变 View 在大单元格中切成两半,并且正如您在下图中看到的那样,渐变颜色真的很糟糕,有些底部颜色非常深,有些颜色偏黄,这使得单元格看起来不一样

我如何设置单元格大小:

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)
}

这就是单元类设置:

 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

最佳答案

由于单元格重用,您的gradient frame 将在单元格几何形状发生变化时变得过时。

在您的 SearchProductsCell 类中,在 layoutSubviews 的 override 中更新 gradientframe :

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

关于ios - UICollectionViewCell,多个单元格大小,设置 gradientView 宽度未设置为当前单元格大小,滚动时有时会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51192224/

相关文章:

ios - 如何实现PT_DENY_ATTACH(iOS中的反调试)

ios - 在应用启动时显示介绍视频

ios - 导航栏 :shouldPop is not functioning as expected

php - Alamofire打印“由于错误,无法序列化JSON:”

iOS推送通知自定义声音无法弄清楚

ios - 当单元格不可见时,如何访问和迭代 UITableView 中的 contentView.subviews?

ios - 如何更改坐标注释的图像?

ios - Firebase - 有效检查用户名被占用

ios - 使用 SwifyStoreKit 在应用内购买无法获取有关产品的信息

json - 如何检测 Alamofire 请求何时为空?