简体   繁体   中英

UIButton subclass highlighting error (highlight remains or persists even after tap or touch down)

I subclassed UIButton in my app and there are many times when the highlight color stays even when I'm done pressing down the button. I can't figure out exactly what causes this since it only seems to happen by chance, but it seems to happen about 50% of the time. I'm very sure that this is reproducible. I often get this to happen when I have a button in a UITableViewCell and I click on it while the table view is still scrolling.

Is there something wrong with the way I'm overriding the setHighlighted method in the subclass? This is my implementation:

@implementation SCPFormButton

- (id)initWithFrame:(CGRect)frame label:(NSString *)label
{
    self = [super initWithFrame:frame];
    if (self) {
        UILabel *buttonLabel = [[UILabel alloc] init];
        buttonLabel.attributedText = [[NSAttributedString alloc] initWithString:[label uppercaseString] attributes:kButtonLabelAttributes];
        [buttonLabel sizeToFit];
        buttonLabel.frame = CGRectMake(kMaxWidth / 2 - buttonLabel.frame.size.width / 2, kStandardComponentHeight / 2 - buttonLabel.frame.size.height / 2, buttonLabel.frame.size.width, buttonLabel.frame.size.height);
        [self addSubview:buttonLabel];

        self.backgroundColor = kFormButtonColorDefault;
    }
    return self;
}

- (void)setHighlighted:(BOOL)highlighted
{
    self.backgroundColor = highlighted ? kFormButtonColorHighlighted : kFormButtonColorDefault;
    [self setNeedsDisplay];
}

@end

I would try to call super in your setHighlighted override. Indeed, Apple docs for UIControl state:

Specify YES if the control is highlighted; otherwise NO. By default, a control is not highlighted. UIControl automatically sets and clears this state automatically when a touch enters and exits during tracking and when there is a touch up.

So, it seems there is some kind of state handling going on in UIControl associated with this.

If this does not help, I would try to add a log trace so you can check which state the button is in when the touch is handled.

You are missing the call to super. But, anyway, subclassing UIButton is not recommended, I would try to do it using setBackgroundImage:forState instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM