我在这个类中有 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)
}
}
最佳答案
由于单元格重用,您的gradient
frame
将在单元格几何形状发生变化时变得过时。
在您的 SearchProductsCell
类中,在 layoutSubviews 的
:override
中更新 gradient
的 frame
override func layoutSubviews() {
super.layoutSubviews()
if isGradientAdded {
gradientView.layer.sublayers?.first?.frame = self.bounds
}
}
关于ios - UICollectionViewCell,多个单元格大小,设置 gradientView 宽度未设置为当前单元格大小,滚动时有时会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51192224/