3

I have a UIButton that has a white image of an arrow.

What I want to do is to change the buttons background color and keep the image as white while the button is pushed down.

I have tried this:

@IBAction func backButtonDidTouch(sender: AnyObject) {

        backButton.backgroundColor = UIColor.blueColor()

    }

But this will give the button a blue color soon as I lift my finger. I want the background color to change soon as I touch/press down the button. And also keep the image white.

Thanks

2
  • how can you see the background color,if the button is covered with the image? Commented Jul 21, 2015 at 15:01
  • In storyboard I've set image to a image, and not background Commented Jul 21, 2015 at 15:06

3 Answers 3

4

you can change background color on UIButton

first you should create a util class.

class Color {
    class func imageWithColor(color: UIColor, size: CGSize = CGSizeMake(60, 60)) -> UIImage {
        var rect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContext(rect.size)
        var context = UIGraphicsGetCurrentContext()

        CGContextSetFillColorWithColor(context, color.CGColor);
        CGContextFillRect(context, rect);

        var image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext();

        return image;
    }
}

next you can set highlight color for UIButton

UIButton type must be 'Custom'

func viewDidLoad() {
    backButton.setBackgroundImageForState(Color.imageWithColor(UIColor.blueColor()), forState: .Highlighted))   
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use setBackgroundImage(_:forState:) to change background for Selected state

3 Comments

Wont that just change the image and not the background color?
have two images with diff colors.
UIButton have a image and backgroundImage, you change backgroundImage for state Selected only
0

When creating the action method in the interface builder, you can choose the event type. It's in the same dialog where you choose the name of your method.

You've chosen the default Touch Up Inside.

Choose event Touch Down instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.