【发布时间】:2020-12-21 06:12:39
【问题描述】:
我正在开发一个以编程方式创建其所有 UI 的 iOS 项目。不是故事板。
我想给 UIViewController 的 UIView 的背景添加一个渐变。
我创建了以下扩展方法。
extension UIView {
func addGradient(colors: [UIColor]) {
let gradientLayer = CAGradientLayer()
gradientLayer.bounds = bounds
gradientLayer.colors = colors.map { $0.cgColor }
layer.insertSublayer(gradientLayer, at: 0)
}
}
我像这样在 ViewController 的viewDidLoad 中添加了渐变。
let topColor = UIColor(red: 0.28, green: 0.521, blue: 0.696, alpha: 1)
let bottomColor = UIColor(red: 0.575, green: 0.615, blue: 0.692, alpha: 1)
view.addGradient(colors: [topColor, bottomColor])
但渐变并未应用到屏幕的全宽和全高。
我打印出视图的边界,它显示了这些值。
(0.0, 0.0, 375.0, 812.0)
所以我不确定为什么渐变仍然没有覆盖整个视图。
【问题讨论】:
-
in View 是否布局子视图更新了渐变的框架,不应该设置边界,改用框架
-
@PrashantTukadiya 我也试过了。仍然没有改变任何东西。
-
@matt 我将渐变设置代码移到了
viewDidLayoutSubviews,但由于某种原因它仍然不起作用。 Demo
标签: ios swift calayer bounds cagradientlayer