在 Swift 中的按钮上设置背景渐变 [英] Set Background Gradient on Button in Swift
问题描述
我不知道如何在按钮上设置背景渐变(不使背景渐变成为图像).这与 Android 有很大不同.
I have no idea how to set the background gradient on a button (without making the background gradient an image). This is so different from Android.
这是一个我必须定义可返回渐变方案的类:
Here's a class I have to define a returnable gradient scheme:
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
}
}
我可以使用它来设置整个视图的背景,如下所示:
I can use this to set the background of my entire view with the following:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let background = CAGradientLayer().backgroundGradientColor()
background.frame = self.view.bounds
self.view.layer.insertSublayer(background, atIndex: 0)
}
//...
}
但是我怎样才能访问按钮的视图并插入子图层或类似的东西?
But how can I access the view of the button and insert the sublayer or something like that?
推荐答案
您的代码运行良好.你只需要记住每次设置渐变的框架.最好让渐变类别也为您设置视图的框架.
Your code works fine. You just have to remember to set the gradient's frame every time. It is better to just make the gradient category also set the frame of the view for you.
这样你就不会忘记并且它适用.
That way you don't forget and it applies fine.
import UIKit
extension UIView {
func applyGradient(colours: [UIColor]) -> CAGradientLayer {
return self.applyGradient(colours: colours, locations: nil)
}
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])
}
}
按钮是视图.将渐变应用于它的方式与将其应用于任何其他视图的方式相同.
Buttons are views. You apply gradients to it the same way you would apply it to any other view.
图片证明:
视频证明:https://i.imgur.com/ssDTqPu.mp4
这篇关于在 Swift 中的按钮上设置背景渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!