使用此代码,我可以使用渐变添加背景到UIButton:
public func addBackgroundAndGradient(to: UIView, gradient1: CGColor, gradient2: CGColor, cornerRadius: CGFloat = 5){
let backgroundImage = UIImageView()
backgroundImage.frame.size = to.frame.size
backgroundImage.clipsToBounds = true
backgroundImage.layer.borderColor = UIColor.white.cgColor
backgroundImage.layer.borderWidth = 0.5
to.insertSubview(backgroundImage, at: 0)
let gradient = CAGradientLayer()
let gradient1 = UIColor(red: 200/255, green: 100/255, blue: 5/255, alpha: 1).cgColor
let gradient2 = UIColor(red: 1, green: 128/255, blue: 0, alpha: 1).cgColor
gradient.colors = [gradient1, gradient2, gradient2, gradient1]
gradient.locations = [0.0, 0.35, 0.65, 1.0]
gradient.frame.size = to.frame.size
backgroundImage.layer.addSublayer(gradient)
backgroundImage.layer.cornerRadius = cornerRadius
}
但是,当我为UIButton设置新标题时,背景将不会调整大小。当文本长于初始时,文本将超出背景。
如何使用UIButton的渐变调整背景大小?
答案 0 :(得分:0)
为此,您需要创建自定义UIButton子类,并将CAGradientLayer设置为其图层类:
class ExpandableGradientButton: UIButton {
override class var layerClass: AnyClass {
get {
return CAGradientLayer.self
}
}
}
然后,您需要将您的功能更改为:
@IBOutlet weak var expandableGradientButton: ExpandableGradientButton!
...
public func addBackgroundAndGradient(to: UIView, gradient1: CGColor, gradient2: CGColor, cornerRadius: CGFloat = 5){
let backgroundImage = UIImageView()
backgroundImage.frame.size = to.frame.size
backgroundImage.clipsToBounds = true
backgroundImage.layer.borderColor = UIColor.white.cgColor
backgroundImage.layer.borderWidth = 0.5
let gradient1 = UIColor(red: 100/255, green: 140/255, blue: 2/255, alpha: 1).cgColor
let gradient2 = UIColor(red: 123/255, green: 158/255, blue: 54.0/255.0, alpha: 1).cgColor
if let butonLayer = to.layer as? CAGradientLayer
{
butonLayer.colors = [gradient1, gradient2, gradient2, gradient1]
butonLayer.locations = [0.0, 0.35, 0.65, 1.0]
butonLayer.cornerRadius = cornerRadius
}
}
换句话说,您必须使用渐变图层作为UIButton的图层,并且它将自动调整大小。 注意:这也可以用于任何其他UIView子类,不仅适用于UIButton。