gpt4 book ai didi

ios - 为什么 UITableViewCell 中的渐变层没有覆盖整个框架?

转载 作者:可可西里 更新时间:2023-10-31 23:57:29 25 4
gpt4 key购买 nike

我尝试用长 UIView 制作一个标准的上下渐变。但它还没有满。 nib 是 UITableViewCell 的一部分,因此我无权访问 viewDidLayoutSubviews(),如 this thread 中所示.

enter image description here

我已尝试从此 View 的代码版本调用 contentView.layoutIfNeeded()。我在调用 UITableView cellForRowAtIndexPath 时调用了它。但是没有效果。

我在 awakeFromNib() 中准备渐变。

let colors = [
UIColor(red: 33/255.0, green: 33/255.0, blue: 33/255.0, alpha: 1.0).cgColor,
UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1.0).cgColor]
let gradient = CAGradientLayer()
gradient.frame = gradientView.bounds
gradient.colors = colors
gradientView.layer.insertSublayer(gradient, at: 0)

我的代码有问题吗?

最佳答案

您应该使用 View 的bounds而不是frame,因为您的图层在 View 内部,而frame 可能有偏移量。

View 的布局在 awakeFromNib 之后发生了变化。因此,您应该在 View 的 layoutSubviews 中调整图层的大小。为此创建一个属性 gradient 和:

let gradient: CAGradientLayer = CAGradientLayer()

override func awakeFromNib() {
...
let colors = [
UIColor(red: 33/255.0, green: 33/255.0, blue: 33/255.0, alpha: 1.0).cgColor,
UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1.0).cgColor]
gradient.frame = bounds
gradient.colors = colors
gradientView.layer.insertSublayer(gradient, at: 0)
...
}

override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = bounds
}

编辑:另一种方法是使用自己的图层类的自定义 View :

public class GradientLayer: UIView {
@IBInspectable var startColor: UIColor! = UIColor(red: 33/255.0, green: 33/255.0, blue: 33/255.0, alpha: 1.0)
@IBInspectable var endColor: UIColor! = UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1.0)

override class var layerClass : AnyClass {
return CAGradientLayer.self
}
override func awakeFromNib() {
super.awakeFromNib()
let colors = [ startColor.cgColor, endColor.cgColor ]
if let gradient = self.layer as? CAGradientLayer {
gradient.colors = colors
}
}
}

这更优雅,因为您可以用 IB inspectables 替换静态颜色,并且您有一个可重用的组件 View 。

关于ios - 为什么 UITableViewCell 中的渐变层没有覆盖整个框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47937307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com