Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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!

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];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top