因此,我有一个自定义的 UICollectionViewController ,其中包含简单的矩形单元格( UICollectionViewCell )。我想用圆角和渐变背景色自定义这些。我可以通过在viewcontroller中为单元格设置适当的参数来实现。
但是,在旋转的情况下,我的单元格“崩溃”,就像渲染出现问题。您是否认为我缺少某些东西,还是应该以完全不同的方式做到这一点?
override func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = self.collectionView
.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier,
for: indexPath) as? AllCollectionViewCell else {
fatalError("The dequeued cell is not an instance of AllCollectionViewCell.")
}
// Configure the cell
cell.layer.cornerRadius = 15;
cell.layer.masksToBounds = true
let gradientLayer = CAGradientLayer()
gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.colors = [UIColor.red.withAlphaComponent(0.3).cgColor,
UIColor.red.withAlphaComponent(0.7).cgColor]
gradientLayer.frame = cell.bounds
cell.backgroundView = UIView()
cell.backgroundView?.layer.addSublayer(gradientLayer)
return cell
}
问题并非绝对可预见,但在旋转(横向查看后又回到纵向)和滚动之后,该问题经常发生。
https://i.imgur.com/tGvauZG.png
答案 0 :(得分:0)
我已经尝试过了,但是没有遇到UI错误。请将您的验证码发送给我,让我检查是否需要。
但是我想通常来说,为了更好的实践,您应该将单元UI代码移到其单元类AllCollectionViewCell
答案 1 :(得分:0)
我尝试按照canister_exister和Mohamed Shaban的建议在单元格类本身(AllCollectionViewCell)中设置属性,并部分解决了它:
*ngFor
但是,gradientLayer的帧不符合我的期望,所以我进一步搜索了一下,发现应该将其放置在另一个函数中。因此,我将gradientLayer移至类属性,然后覆盖了此函数:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 15;
self.layer.masksToBounds = true
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5)
self.backgroundView = UIView()
self.backgroundView?.layer.addSublayer(gradientLayer)
}