Bhanuteja
Bhanuteja

Reputation: 801

How to set gradient colour to UIButton in background?

Am trying to set CAGradientLayer for UIButton.

But it is not getting exactly. am I doing any wrong ?

am getting output like

this

You can see there is some horizontal line

Here is the code which I tried

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)

Upvotes: 0

Views: 161

Answers (2)

Shakti
Shakti

Reputation: 996

Create a Designable custom class like this

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)

    }
}

from your Identity inspector set your UIbutton class to CustomButtom like this enter image description here

from your Attribute inspector change your gradient color to whatever you want to set enter image description here

and finally your button will be like this enter image description here

if you want to change the starting and endpoint to those colors just play around with these two values

gradient.startPoint = CGPoint(x: 0.0, y: 1.0) gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

Upvotes: 2

André Slotta
André Slotta

Reputation: 14030

You have to update the gradient's frame when the view is laid out:

override func viewDidLayoutSubviews() {
    myButton.layer.sublayers?.first?.frame = myButton.bounds
}

Upvotes: 0

Related Questions