5

I am drawing custom a UIButton and want to set the blue color when it is highlighted. How can I achieve this?

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setBackgroundImage:[[UIImage imageNamed:@"test.png"] stretchableImageWithLeftCapWidth:100 topCapHeight:0] forState:UIControlStateNormal];
Abhinav
  • 37,684
  • 43
  • 191
  • 309
  • It is not a duplicate. The linked question does not address the highlight color, only the background color. – len Feb 13 '13 at 15:57
  • Hey, [I made a category that helps you to achieve this](https://github.com/NSElvis/UIButton-ANDYHighlighted). – 3lvis Dec 07 '14 at 14:35

5 Answers5

3

Ya, you can create a 1px by 1px "blue colored" image and use the following:

[yourButton setBackgroundImage:[UIImage imageNamed:@"theImageYouMade.png"] forState:UIControlStateHighlighted];

You can't use "setImage:" in my method because the highlighted state of the button will actually just display the 1px by 1px image in the center of the button.

My method works for variable sized buttons. Using setImage: requires you to make images that are exactly the same size as your button.

-Chris

Chris Allinson
  • 1,837
  • 2
  • 26
  • 39
  • And if the color is dynamic [see how to create image from color](https://stackoverflow.com/a/33675160/8740349) – Top-Master Apr 15 '21 at 15:24
3

You can do following to set images for your state (normal/highlight/selected). You have to have images.

[downButton setImage:[UIImage imageNamed:@"white.png"] forState:UIControlStateNormal];
[downButton setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateHighlighted];
MobileSoul
  • 31
  • 2
2

You can try to use another image to do the job. You can also refer to this link:

Is it even possible to change a UIButtons background color?

Community
  • 1
  • 1
Sola
  • 1,512
  • 4
  • 15
  • 31
  • 5
    If another SO question answers this one so completely that all you have to do is link to it, please flag to close as a duplicate rather than posting. – jscs May 20 '11 at 03:25
  • 4
    It is not a duplicate. The linked question does not address the highlight color, only the background color. – len Feb 13 '13 at 15:05
0

Maybe set a different background image for a different state?

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
0

Provide a background image for UIControlStateHighlighted. Also it might help to turn off adjustsImageWhenHighlighted, though this should not matter if you're providing a separate background image for the highlighted state.

matt
  • 515,959
  • 87
  • 875
  • 1,141