我正在尝试为UIButton
设置 CAGradientLayer 。
但是并没有完全正确。我做错了吗?
我获得
之类的 输出您会看到一条水平线
这是我尝试的代码
let topColor = UIColor(red: 0.62, green: 0.38, blue: 1, alpha: 1).cgColor
let bottomColor = UIColor(red: 0.87, green: 0.51, blue: 0.93, alpha: 1).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = myButton.bounds
gradientLayer.colors = [topColor, bottomColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
myButton.layer.insertSublayer(myButton, at: 0)
答案 0 :(得分:2)
像这样创建一个可设计的自定义类
import Foundation
import UIKit
@IBDesignable class CustomButton:UIButton {
@IBInspectable var firstColor:UIColor = UIColor.clear {
didSet {
updateUI()
}
}
@IBInspectable var secondColor:UIColor = UIColor.clear {
didSet{
updateUI()
}
}
override class var layerClass: AnyClass {
get {
return CAGradientLayer.self
}
}
func updateUI(){
let gradient: CAGradientLayer = self.layer as! CAGradientLayer
gradient.frame = self.bounds
gradient.colors = [firstColor,secondColor].map { $0.cgColor }
gradient.locations = [0.0,1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
}
}
从您的身份检查器中
如果要将起点和终点更改为这些颜色 只需使用这两个值
gradient.startPoint = CGPoint(x:0.0,y:1.0) gradient.endPoint = CGPoint(x:1.0,y:1.0)
答案 1 :(得分:0)
布局视图时,您必须更新渐变的框架:
override func viewDidLayoutSubviews() {
myButton.layer.sublayers?.first?.frame = myButton.bounds
}