我不知道如何在按钮上设置背景渐变(不使背景渐变成为图像)。这与Android截然不同。
这是我必须定义一个可返回的渐变方案的类:
import UIKit extension CAGradientLayer { func backgroundGradientColor() -> CAGradientLayer { let topColor = UIColor(red: (0/255.0), green: (153/255.0), blue:(51/255.0), alpha: 1) let bottomColor = UIColor(red: (0/255.0), green: (153/255.0), blue:(255/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 } }
我可以使用以下方法设置整个视图的背景:
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let background = CAGradientLayer().backgroundGradientColor() background.frame = self.view.bounds self.view.layer.insertSublayer(background, atIndex: 0) } //... }
但是,如何访问按钮的视图并插入子层或类似内容?
您的代码工作正常。您只需要记住每次都要设置渐变的帧。最好仅使渐变类别也为您设置视图的框架。
这样,您就不会忘记,它也很好。
import UIKit extension UIView { @discardableResult func applyGradient(colours: [UIColor]) -> CAGradientLayer { return self.applyGradient(colours: colours, locations: nil) } @discardableResult func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> CAGradientLayer { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = self.bounds gradient.colors = colours.map { $0.cgColor } gradient.locations = locations self.layer.insertSublayer(gradient, at: 0) return gradient } } class ViewController: UIViewController { @IBOutlet weak var btn: UIButton! override func viewDidLoad() { super.viewDidLoad() self.btn.applyGradient(colours: [.yellow, .blue]) self.view.applyGradient(colours: [.yellow, .blue, .red], locations: [0.0, 0.5, 1.0]) } }
按钮是视图。对其应用渐变的方式与将其应用于任何其他视图的方式相同。
图片证明:
影片证明: https : //i.imgur.com/ssDTqPu.mp4