0

I'm trying to make a UIBarButtonItem behave like the "view mode" button in the iOS 7 calendar app. When tapped it becomes highlighted and stays this way until it's tapped again.

Example image (can't embed images yet, sorry)

I have already tried setting the BackgroundImage property to a image with forState:(UIControlStateHighlighted | UIControlStateSelected) as suggested here, nothing happens.

Community
  • 1
  • 1
tuco94
  • 35
  • 6

1 Answers1

0

I think you should use a custom view. See this example using a 40x40 button

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0,0,40,40);

    [button setBackgroundImage:[UIImage imageNamed:@"button.png"]  forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"buttonSelected.png"]  forState:UIControlStateSelected];
    [button addTarget:self action:@selector(didTouchButton:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:buttonItem, nil]];

And in the touch set selected

- (void) didTouchButton:(id)sender
{
    UIButton *button = (UIButton*)sender;
    button.selected = YES;

    //Do stuff
}
dminones
  • 2,236
  • 20
  • 21
  • Your ideia seems good but have you tested it in iOS7 or 8? The button does not ever appear now. – tuco94 Jan 28 '15 at 23:05
  • I didn't test this code but this approach works on both ios7 and ios8, will try to share working code – dminones Jan 28 '15 at 23:26
  • Now the image change when tapped but it's not permanent. The button image does not stays selected until it's tapped again. – tuco94 Jan 29 '15 at 00:13
  • Jus updated the answer, you need to ser as selected the button – dminones Jan 29 '15 at 00:22
  • I ended up using the UIbarButtonItem and changing it's image at run time, didn't thought it would work. Is it bad pratice? Accepting your answer as it solves the problem as well. Thanks. – tuco94 Jan 29 '15 at 00:27
  • Thanks. It's better the selected approach since you use the property on unbutton to track the state , for instance if you want to know if the button is selected you – dminones Jan 29 '15 at 00:31