gpt4 book ai didi

swift - iOS8:自动布局和渐变

转载 作者:行者123 更新时间:2023-11-28 09:34:45 24 4
gpt4 key购买 nike

设置:

我有一个 View Controller,它由一个 View 和一个 Container View 组成。

enter image description here

View (橙色)被固定top 0、left 0 和right 0.

容器 View (灰色)被固定底部 0、左侧 0 和 0.

ViewBottom Space to: Container View = 0

ViewProportional Height to Container View = 1

期望的结果:我想为 View(橙色)

的背景添加渐变

尝试过:

我正在使用具有类大小的自动布局来在不同的屏幕上获得不同的行为。

代码:

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
}
}

结果:

enter image description here

如您所见,渐变并没有覆盖整个View

问题:如何让渐变覆盖整个View

更新:

当我将代码放在 viewDidLayoutSubviews() 中时,旋转时看起来很奇怪:

enter image description here

最佳答案

只需在 viewDidLayoutSubviews 中执行此操作即可:

override func viewDidLayoutSubview() {
super.viewDidLayoutSubviews
backgroundColor.frame = self.graphView.bounds
}

viewDidLayoutSubviews 应该在您旋转设备时被调用。

如果它没有被调用,重写这个方法并按照,

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

backgroundColor.frame = self.graphView.bounds
}

关于swift - iOS8:自动布局和渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31172151/

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