我为您创建了一个演示,您可以借助CAGradientLayer
来实现此操作,请查看以下输出和代码。
![enter image description here](https://istack.dev59.com/w2r8E.webp)
故事板:
![enter image description here](https://istack.dev59.com/ya0h1.webp)
要为渐变按钮文本颜色和边框设置,请将UIButton
放入UIView
中,然后将CAGradientLayer
分配给UIview
。
注意:不要忘记将按钮设置为视图的蒙版,请参见以下代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet var viewForButton: UIView!
@IBOutlet var myButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let gradient = CAGradientLayer()
gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.frame = viewForButton.bounds
viewForButton.layer.insertSublayer(gradient, at: 0)
viewForButton.mask = myButton
myButton.layer.cornerRadius = myButton.frame.size.height / 2
myButton.layer.borderWidth = 5.0
}
}
扩展: 您也可以考虑此扩展程序。
extension UIView{
func gradientButton(_ buttonText:String, startColor:UIColor, endColor:UIColor) {
let button:UIButton = UIButton(frame: self.bounds)
button.setTitle(buttonText, for: .normal)
let gradient = CAGradientLayer()
gradient.colors = [startColor.cgColor, endColor.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.frame = self.bounds
self.layer.insertSublayer(gradient, at: 0)
self.mask = button
button.layer.cornerRadius = button.frame.size.height / 2
button.layer.borderWidth = 5.0
}
}
如何使用:
testView.gradientButton("Hello", startColor: .red, endColor: .blue)