gpt4 book ai didi

ios - 如何将渐变应用于 iOS Swift 应用程序的背景 View

转载 作者:IT王子 更新时间:2023-10-29 04:55:25 26 4
gpt4 key购买 nike

我正在尝试将渐变应用为 View ( Storyboard的主视图)的背景色。代码运行,但没有任何变化。我正在使用 xCode Beta 2 和 Swift。

代码如下:

class Colors {
let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0)
let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0)

let gl: CAGradientLayer

init() {
gl = CAGradientLayer()
gl.colors = [ colorTop, colorBottom]
gl.locations = [ 0.0, 1.0]
}
}

然后在 View Controller 中:

  let colors = Colors()

func refresh() {
view.backgroundColor = UIColor.clearColor()
var backgroundLayer = colors.gl
backgroundLayer.frame = view.frame
view.layer.insertSublayer(backgroundLayer, atIndex: 0)
}
}
}

最佳答案

Xcode 11 • Swift 5.1


您可以按如下方式设计自己的渐变 View :

@IBDesignable
public class Gradient: UIView {
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() }}
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() }}
@IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }}
@IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }}
@IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }}
@IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }}

override public class var layerClass: AnyClass { CAGradientLayer.self }

var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }

func updatePoints() {
if horizontalMode {
gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
gradientLayer.endPoint = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
} else {
gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
gradientLayer.endPoint = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
}
}
func updateLocations() {
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
}
func updateColors() {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updatePoints()
updateLocations()
updateColors()
}

}

enter image description here

关于ios - 如何将渐变应用于 iOS Swift 应用程序的背景 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24380535/

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