用于设置按钮高度的UIButton子类Xcode/Swift
问题描述:
我创建了一个UIButton子类来为一批按钮添加一个渐变图层,并且想知道是否有方法来设置按钮的高度,因为它们都将是一样的高度。这是我的渐变层,所以我想知道,如果它是可能的,代码在代码中,我需要把它:用于设置按钮高度的UIButton子类Xcode/Swift
public class GradientButton: UIButton {
override public func layoutSubviews() {
super.layoutSubviews()
createGradientBackground()
}
func createGradientBackground() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.layer.bounds
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha:1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha:1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.layer.insertSublayer(gradientLayer, atIndex: 0)
}
}
答
当然,只需添加:
init() {
self.frame.size.height = 50.0
//Do other stuff you may want
}
OR:
func createGradientBackground() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.layer.bounds
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha:1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha:1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.layer.insertSublayer(gradientLayer, atIndex: 0)
//set custom height wanted
self.frame.size.height = 50.0
}
您可以在自定义init()或createGradientBackground()的内部执行此操作。但是,您必须记住您在故事板中按钮上设置的约束条件。