Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change image and disable UIBarButtonItem

I have a NavigationBar app with two views: a parent and a sub view. In the sub view I'm adding a button to the right corner as follows:

- (void)viewDidLoad {
    UIBarButtonItem *tempButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"lock-unlocked.png"] style:UIBarButtonItemStylePlain target:self action:@selector(lockScreen)];
    self.navigationItem.rightBarButtonItem = tempButton;
    [tempButton release];
}

When that button is clicked I want to change the image of this rightBarButtonItem and disable the leftBarButtonItem (which was added automatically by the controller). Basically have two states of a button, locked and unlocked.

Question 1: The only way I can find how to change the image is to create a new UIButtonItem with a new image and replace rightBarButtonItem with that new one. But I'm wondering if there's a way to just change the image without creating a new UIBarButtonItem. Am I creating a memory leak if I keep creating new UIBarButtonItem?

Question 2: How can I get a hold of self.navigationItem.leftBarButtonItem and disable/enable it? I don't create that one manually, it's created automatically for me by the controller. I don't see any method/property on UIBarButtonItem to enable/disable user interaction with it.

like image 954
subjective-c Avatar asked Feb 11 '09 11:02

subjective-c


3 Answers

Question 1: Declare UIBarButtonItem *tempButton in the interface

@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
    UIBarButtonItem *tempButton;
}

@property (nonatomic, retain) UIBarButtonItem *tempButton;

and synthesize it in the implementation.

@synthesize tempButton;

Create the object in viewDidLoad similiar to how you are now.

- (void)viewDidLoad {
  tempButtom = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"lock-unlocked.png"] style:UIBarButtonItemStylePlain target:self action:@selector(lockScreen)];
  self.navigationItem.rightBarButtonItem = tempButton;
}

But don't release it here, release it in the dealloc method normally found at the bottom.

Then when lockScreen is called do

tempButton.image = [UIImage imageNamed:@"myImage.png"]

I don't have an answer for question 2, im afraid!

like image 140
Gcoop Avatar answered Oct 28 '22 04:10

Gcoop


In regard to question 2, use the 'enabled' property:

 self.navigationItem.leftBarButtonItem.enabled = NO;
like image 35
eelco Avatar answered Oct 28 '22 05:10

eelco


I can't understand if you have a navigationController, but in this case to disable the back button you need to call:

self.navigationItem.hidesBackButton = YES;
like image 5
Dzamir Avatar answered Oct 28 '22 06:10

Dzamir