Kiwo Tew
Kiwo Tew

Reputation: 1531

Swift change button background color and image color while pressed

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

Upvotes: 3

Views: 9973

Answers (3)

Gerd Castan
Gerd Castan

Reputation: 6859

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.

Upvotes: 0

kimwz.kr
kimwz.kr

Reputation: 298

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

Upvotes: 4

Andrei L
Andrei L

Reputation: 3681

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

Upvotes: 0

Related Questions