drawRect not called for custom UIButton subclass when highlighted

坚强是说给别人听的谎言 提交于 2019-11-29 23:11:47

问题


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?


回答1:


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.




回答2:


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!




回答3:


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


来源:https://stackoverflow.com/questions/823524/drawrect-not-called-for-custom-uibutton-subclass-when-highlighted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!