3

When using drawRect for a custom UIButton subclass, it never seems to get called to draw the button when highlighted. Do I need to call setNeedsDisplay for my button in my touch events?

Pang
  • 9,564
  • 146
  • 81
  • 122
mahboudz
  • 39,196
  • 16
  • 97
  • 124
  • Answer here: http://stackoverflow.com/questions/4022763/change-background-color-of-uibutton-when-highlighted – GoldenBoy Dec 02 '11 at 21:45

3 Answers3

13

I found an easy solution.

Just add the following method to your UIButton subclass:

-(void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];
    [self setNeedsDisplay];
}

That's it!

Pang
  • 9,564
  • 146
  • 81
  • 122
nilsou
  • 241
  • 2
  • 7
6

As far as i can tell there is no straight forward way to subclass UIButton.

UIButton is not the actual class type that is returned by the initializers. UIButton is kind of a front for a series of private classes.

Say you had:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSLog(@"myButton type: %@", [myButton description]);

You will find the type returned in the log to be "UIRoundedRectButton". The problem with that is you would need to have extended "UIRoundedRectButton". That is not possible as it is a private class which is only ever returned to UIButton.

On top of that "UIRoundedRectButton" is not the only possible returned class all of which are private.

In other words UIButton was built in manner that is not suited to be extended.

abe
  • 4,046
  • 6
  • 29
  • 33
  • Yes, that's sort of what I have discovered. Plus, UIButton doesn't seem to use drawRect to draw itself. It calls my drawRect and then goes ahead and blasts whatever bitmap right over what I draw - and I am not calling the super's drawRect. I have subclassed UIControl instead, although I miss the tap highlighting that UIButton was providing. – mahboudz Jul 08 '09 at 04:42
  • its a pain but i dont think apple want us extending the class...wether its cause the class cant handle it or they are forcing use to follow there vision for the structure of the language i just dont know :) – abe Jul 08 '09 at 08:37
1

I had the same problem and satisfying success with the following added to my UIButton subclass

- (void)awakeFromNib {
    [self addTarget:self action:@selector(redraw) forControlEvents:UIControlEventAllEvents];
}

- (void)redraw {
    [self setNeedsDisplay];
    [self performSelector:@selector(setNeedsDisplay) withObject:self afterDelay:0.15];
}
Sebastian
  • 2,109
  • 1
  • 20
  • 15