jessica mele jessica mele - 26 days ago 14
iOS Question

Adding a Gradient Layer to all buttons with the same name Xcode/Swift

So new-ish to Xcode/Swift and I'm adding a gradient layer to a bunch of buttons in different View Controllers in my app. I am wondering if there is a way to target all of the buttons with a specific name at once, rather than add my code into each page individually. Here is my gradient code:

let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.btnSavePhoto.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.btnSavePhoto.layer.addSublayer(gradientLayer)

Answer

You can create a custom class for making your UIButton with Gradient somehow like this

For Swift 3

import UIKit

public class GradientButton: UIButton {

    override public func layoutSubviews() {
        super.layoutSubviews()
        layoutGradientButtonLayer()
    }

    // MARK: Private
    private func layoutGradientButtonLayer() {
        let gradientLayer = CAGradientLayer()
        let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).cgColor as CGColor
        let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).cgColor as CGColor
        gradientLayer.colors = [color1, color2]
        gradientLayer.locations = [0.0, 1.0]
        self.layer.addSublayer(gradientLayer)
    }
}

For Swift 2.3

import UIKit

public class GradientButton: UIButton {

    override public func layoutSubviews() {
        super.layoutSubviews()
        layoutGradientButtonLayer()
    }

    // MARK: Private
    private func layoutGradientButtonLayer() {
         let gradientLayer = CAGradientLayer()
         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.addSublayer(gradientLayer)
    }
}

Then in the inspector for button you can set the Class as GradientButton check the image

enter image description here

In this way you don't need to write the code for your button for gradient.

Comments