在UIView上应用渐变不起作用 [英] Apply gradient on a UIView not working
问题描述
我正在尝试以编程方式将渐变添加到UIView,但是它不起作用.它似乎根本没有颜色.我已经附上了相关代码以及屏幕截图.请注意我正在应用渐变的底部正方形.有人可以帮我弄清楚我在做什么错吗?
I am trying to add gradient to a UIView programmatically but it is not working. It just appears to have no color at all. I have attached the relevant code as well as a screenshot. Notice the bottom square over which i am applying the gradient. Can someone help me figure out what I'm doing wrong here?
let sundayView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupSundayView()
}
func setupViews() {
sundayView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(sundayView)
}
func setupSundayView() {
sundayView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
sundayView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor),
sundayView.topAnchor.constraintEqualToAnchor(fridayView.bottomAnchor, constant: 16.0),
sundayView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor, constant: -8.0),
sundayView.heightAnchor.constraintEqualToAnchor(mondayView.heightAnchor),
sundayView.widthAnchor.constraintEqualToAnchor(mondayView.widthAnchor)
])
let gradient = CAGradientLayer()
gradient.frame = sundayView.bounds
gradient.colors = [
UIColor(red:1.00, green:0.37, blue:0.23, alpha:1.0).CGColor,
UIColor(red:1.00, green:0.16, blue:0.41, alpha:1.0).CGColor
]
sundayView.layer.insertSublayer(gradient, atIndex: 0)
}
推荐答案
您的渐变未显示,因为 sundayView
的 bounds
直到自动版式开始运行.覆盖 viewDidLayoutSubviews
并在那里设置渐变框架.
Your gradient isn't showing because the bounds
for sundayView
will not be set until Auto Layout runs. Override viewDidLayoutSubviews
and set the gradient frame there.
将此属性添加到您的viewController中:
Add this property to your viewController:
var sundayGradient: CAGradientLayer?
在 setupSundayView
中,将 gradient
保存到属性:
let gradient = CAGradientLayer()
sundayGradient = gradient
然后在 viewDidLayoutSubviews
中设置框架:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
sundayGradient?.frame = sundayView.bounds
}
这篇关于在UIView上应用渐变不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!