I've got two viewControllers who each need a login button in the top right corner of the navigation bar.
In viewController1#viewDidLoad, I set up the rightBarButtonItem
like so (abbreviated):
// set up the login button on the right
UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *loginImage = [UIImage imageNamed:@"btn_login.png"];
[loginButton setBackgroundImage:loginImage forState:UIControlStateNormal];
[loginButton setFrame:CGRectMake(0, 0, loginImage.size.width, loginImage.size.height)];
[loginButton setTag:1111111];
UIBarButtonItem *loginItem = [[UIBarButtonItem alloc] initWithCustomView:loginButton];
self.navigationItem.rightBarButtonItem = loginItem;
[loginItem release];
I tag it so that in viewWillAppear
, I can use viewWithTag:1111111
to figure out if it needs to be hidden or visible, based on whether or not the user is logged in. Simple.
((UIButton *)[self.navigationController.view viewWithTag:LOGIN_BUTTON_TAG]).hidden = true;
When viewController2 gets pushed onto the stack, I basically run the same code to set up my rightBarButtonItem
, but I give it a different tag (i.e. 222222).
In viewController2#viewWillAppear, when I look for the viewWithTag:222222
, it comes back as null, and so I can't hide/show it.
I noticed though that if I use the same tag as I used in viewController1 (1111111), I can get to it.
Why is this? My tags are actually set up at the top of the file as constants, so it seems inelegant to copy the random number from vc1 into vc2 just so I can get this to work. Instead, I'd like to understand why vc2's tag isn't getting applied to the rightBarButtonItem
, and why vc1's tag is still preserved even though I'm in a different viewController.
tag
between when you assign thetag
and when you get a view from thetag
– tipycalFlowNSLog
its value +1 before comparing – tipycalFlow