【发布时间】:2019-10-13 17:32:58
【问题描述】:
如何将 UIButton 的背景设置为 CAGradientLayer?
我尝试了以下方法:
func applyGradient(colors: [UIColor], locations: [NSNumber]?) -> Void {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = colors.map { $0.cgColor }
gradient.locations = locations
self.layer.insertSublayer(gradient, at: 0)
}
我从Set Background Gradient on Button in Swift得到的
然后使用它:
let startButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Get Started", for: .normal)
button.setTitleColor(AppSettings.PURPL_COLOR, for: .normal)
button.titleLabel?.font = UIFont(name: "Rubik-Medium", size: 16.0)
return button
}()
startButton.applyGradient(colors: [.red, .blue], locations: nil)
另外,我将按钮的宽度设置为视图的宽度,将高度设置为 50。
但是,当我运行它时,我得到的是:
不应用背景渐变。
【问题讨论】: