Search code examples
swiftgradienttintcolor

Can you have a gradient as a button tintColor?


I have a icon asset in interface builder which I have as my button image. I can change the colour of it using

button.tintColor = UIColor.blueColor()

Can I apply a gradient though to a tintColor property?

UPDATE

For clarity, my png image icon has different shapes, heart, camera, which I have set up as template images. They all have transparent backgrounds.


Solution

  • You can insert CAGradientLayer into your button and apply the tintColor.

    Another way is to subclass the UIButton, and in drawRect, use CoreGraphics to draw the gradient effect like:

    -(void) drawRect:(CGRect)rect
    {
        ... 
        // setup up your tint color for startColor, endColor
        drawLinearGradient(context, rect, startColor, endColor);
    }
    

    If you have a transparent background, you can use your view's layer's mask property to achieve gradient.