jessica mele jessica mele - 24 days ago 19
Swift Question

UIButton subclass to set height of a button Xcode/Swift

I have created a UIButton subclass to add a gradient layer to a batch of buttons and am wondering if there is a way to set the height of the buttons there as well because they'll all be the same height. This is my code for the gradient layer so I'm wondering if it's possible and where in the code I need to put it:

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)
}
}

Answer

Sure, just add:

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
}

You can do this in an custom init(), or inside of your createGradientBackground(). You do have to keep in mind of what constraints you are setting on your buttons in your storyboard however.

Comments