如何解决Swift UICollectionReusableView 在重用时没有更新框架
我尝试使用与装饰项相同的 UICollectionReusableView 构建多个部分。但是当视图在滚动过程中被重用时,ReusableView 内部的gradientLayer 没有更新以满足新的部分大小。我不知道有什么问题。重用 UICollectionReusableView 时如何重置渐变层框架。
class RoundedBackgroundView: UICollectionReusableView {
private var insetView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 6
view.clipsToBounds = true
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
let gradientLayer = CAGradientLayer()
// Set the size of the layer to be equal to size of the display.
gradientLayer.frame = self.bounds
// Set an array of Core Graphics colors (.cgColor) to create the gradient.
gradientLayer.colors = [UIColor(red: 246,green: 186,blue: 58).cgColor,UIColor(red: 233,green: 115,blue: 58).cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0,y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0,y: 0.5)
// Rasterize this static layer to improve app performance.
gradientLayer.shouldRasterize = true
insetView.layer.addSublayer(gradientLayer)
addSubview(insetView)
NSLayoutConstraint.activate([
insetView.leadingAnchor.constraint(equalTo: leadingAnchor,constant: 0),insetView.trailingAnchor.constraint(equalTo: trailingAnchor,insetView.topAnchor.constraint(equalTo: topAnchor),insetView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
解决方法
对于可重用的视图,我总是建议创建一个单独的视图,在该视图中完成所有布局并将其添加到单元格/可重用视图中。
无论如何,问题可能在于,没有在 init 方法中设置边界。 解决此问题的一种方法是将此函数添加到您的可重用视图中。
override func layoutSubviews() {
super.layoutSubviews()
if insetView.bounds.height > 0 {
gradientLayer.frame = insetView.bounds
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。