Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep iPhone UIButton Highlighted

I have the following code snippets:

@interface Foo: UIViewController {
  ...
  UIButton *myButton;
  ...
}

@implementation Foo

- (void) viewDidLoad {
  ...
  myButton.highlighted = YES;
  ...
}

When I run the app, the button is highlighted in blue (default behavior). It works as I expected.

But after pressing the button once, the button is no longer highlighted.

Then, I created an IBAction highlightButton to handle Touch Up Inside event where I explicitly call myButton.highlighted = Yes;. Unfortunately, the button highlight still does not stay.

How can I keep it highlighted in blue even after being pressed?

like image 201
pion Avatar asked Feb 18 '10 17:02

pion


3 Answers

The solution is to do [button setHighlighted:YES] in the next runloop:

- (void)highlightButton:(UIButton *)b { 
    [b setHighlighted:YES];
}

 - (IBAction)onTouchup:(UIButton *)sender {
    [self performSelector:@selector(highlightButton:) withObject:sender afterDelay:0.0];
}
like image 72
Werner Altewischer Avatar answered Nov 03 '22 23:11

Werner Altewischer


The simplest code is here.

dispatch_async(dispatch_get_main_queue(), ^{
    [button setHighlighted:YES];
});
like image 13
mishimay Avatar answered Nov 04 '22 00:11

mishimay


An alternate way to run this is by sending a block to the main operation queue:

-(void)onTouchup:(UIButton*) button
{
    [NSOperationQueue.mainQueue addOperationWithBlock:^{ button.highlighted = YES; }];
}
like image 7
Peter DeWeese Avatar answered Nov 03 '22 22:11

Peter DeWeese