I have a UIViewController with a bunch of buttons that each have a (unique) tag. I wrote the following method:

- (void) highlightButtonWithTag: (NSInteger) tag
{
    UIButton *btn = (UIButton *)[self.view viewWithTag: tag];
    btn.highlighted = YES;
}

What I am trying to do is have a bunch of buttons that each function like a toggle: when I tap one, it should be come active (i.e. highlighted) and the one that was highlighted before should become "un"highlighted.

When the view comes up, I use the viewDidAppear method to set the initial selection:

- (void) viewDidAppear:(BOOL)animated
{
     self.selectedIcon = 1;
     [self highlightButtonWithTag: self.selectedIcon];
}

And this seems to work just fine: when the view comes up, the first button is selected. However, when I try to update stuff through the @selector connected to the buttons, the previous button is "un"highlighted but the button with sender.tag doesn't get highlighted.

- (IBAction) selectIcon:(UIButton *)sender
{
    // "Un"highlight previous button
    UIButton *prevButton = (UIButton *)[self.view viewWithTag: self.selectedIcon];
    prevButton.highlighted = NO;

    // Highlight tapped button:
    self.selectedIcon = sender.tag;
    [self highlightButtonWithTag: self.selectedIcon];
}

What am I missing here?

有帮助吗?

解决方案

The problem is that the system automatically highlights then unhighlights the button on touchDown and touchUp respectively. So, you need to highlight the button again, after it's unhighlighted by the system. You can do by using performSelector:withObject:afterDelay: even with a 0 delay (because the selector is scheduled on the run loop which happens after the system has done it's unhighlighting). To use that method, you have to pass an object (not an integer), so If you modify your code slightly to use NSNumbers, it would look like this,

- (void) highlightButtonWithTag:(NSNumber *) tag {
    UIButton *btn = (UIButton *)[self.view viewWithTag:tag.integerValue];
    btn.highlighted = YES;
}


- (void) viewDidAppear:(BOOL)animated {
    self.selectedIcon = 1;
    [self highlightButtonWithTag: @(self.selectedIcon)];
}


- (IBAction) selectIcon:(UIButton *)sender {
    // "Un"highlight previous button
    UIButton *prevButton = (UIButton *)[self.view viewWithTag: self.selectedIcon];
    prevButton.highlighted = NO;

    // Highlight tapped button:
    self.selectedIcon = sender.tag;
    [self performSelector:@selector(highlightButtonWithTag:) withObject:@(self.selectedIcon) afterDelay:0];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top