mahboudz
mahboudz

Reputation: 39376

drawRect not called for custom UIButton subclass when highlighted

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?

Upvotes: 3

Views: 7144

Answers (3)

nilsou
nilsou

Reputation: 241

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!

Upvotes: 13

Sebastian
Sebastian

Reputation: 2339

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];
}

Upvotes: 1

abe
abe

Reputation: 4136

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.

Upvotes: 6

Related Questions