问题描述
设置:
我有一个 View Controller
,其中包含一个查看
和容器视图
。
I have a View Controller
that consists of a View
and a Container View
.
查看
(橙色)是固定
到顶部
0,左
0,正确
0.
The View
(Orange) is pinned
to top
0, left
0, and right
0.
容器视图
(灰色)是固定
到底部
0,左
0,正确
0。
The Container View
(Gray) is pinned
to bottom
0, left
0, and right
0.
查看
的底部空间:容器视图
= 0
查看
's 容器的比例高度
查看= 1
所需结果:
我想在查看
(橙色)的背景中添加渐变
Desired Results:I would like to add gradient to the background of the View
(Orange)
尝试:
我正在使用类型大小的自动布局来获得不同不同屏幕上的行为。
I'm using Auto-layout with class sizes to get different behavior on different screen.
代码:
class ViewController: UIViewController {
@IBOutlet weak var graphView: UIView!
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let backgroundColor = CAGradientLayer().graphViewBackgroundColor()
backgroundColor.frame = self.graphView.frame
self.graphView.layer.addSublayer(backgroundColor)
}
我有一个类别:
extension CAGradientLayer {
func graphViewBackgroundColor() -> CAGradientLayer {
let topColor = UIColor(red: (160/255.0), green: (160/255.0), blue: (160/255.0), alpha: 1)
let bottomColor = UIColor(red: (52/255.0), green: (53/255.0), blue: (52/255.0), alpha: 1)
let gradientColors: [CGColor] = [topColor.CGColor, bottomColor.CGColor]
let gradientLocations: [Float] = [0.0, 1.0]
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
return gradientLayer
}
}
结果:
正如您所见,渐变并未涵盖整个 View
。
As you can see gradient did not cover the entire View
.
问题:如何让渐变覆盖整个查看
Question: How can I get the gradient to cover the entire View
更新:
当我将代码放入 viewDidLayoutSubviews时()
旋转时看起来很奇怪:
When I place the code in viewDidLayoutSubviews()
It looks weird when I rotate:
推荐答案
只需在viewDidLayoutSubviews中执行此操作:
Simply do it this inside viewDidLayoutSubviews:
override func viewDidLayoutSubview() {
super.viewDidLayoutSubviews
backgroundColor.frame = self.graphView.bounds
}
旋转设备时应调用viewDidLayoutSubviews。
viewDidLayoutSubviews should be called when you rotate the device.
如果未调用,请覆盖此方法并执行此操作,
If it is not called, override this method and do it as,
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
backgroundColor.frame = self.graphView.bounds
}
这篇关于iOS8:自动布局和渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!