简体   繁体   中英

redraw UIButton when pressed

I'm using paintcodeapp to draw my custom button. I've draw two different status "pressed" and "normal"

I need to call setNeedsDisplay when the button is in "pressed status"

I then dispatch the two draws using self.highlighted in the drawRect: method

I've tried with:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addTarget:self action:@selector(didDetectEvent:) forControlEvents:UIControlEventTouchDown];
        [self addTarget:self action:@selector(didDetectEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self addTarget:self action:@selector(didDetectEvent:) forControlEvents:UIControlStateNormal];

    }
    return self;
}

-(void)didDetectEvent:(id)sender {
    [self setNeedsDisplay];
}

but it doesn't work. any suggestion?

I had this same problem (using Swift). I need to set the background and have it show immediately even if it slows the UI for the user. The solution is to make sure it is done on the main thread.

dispatch_async(dispatch_get_main_queue(), {
   testButton?.backgroundColor = .greenColor()
})

Try with:

-(void)didDetectEvent:(id)sender {
    UIButton *btn = (UIButton *)sender;
    [btn setNeedsDisplay];
}

I assumed that it is implemented in a generic view that has the button you want to manage.

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        [self addTarget:self action:@selector(didDetectEvent:) forControlEvents:UIControlEventAllTouchEvents];
    }
}


  -(void)didDetectEvent:(id)sender {
        [self setNeedsDisplay];
        [self performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:0.2];
}

this works. I'm not completely confident this is the best solution.

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