rightbarbuttonitem not displaying
I have got following code for putting rightbarbuttonitem
UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
[rightbutton setBackgroundImage:[UIImage imageNamed:@"share-icon.png"] forState:UIControlStateNormal];
[rightbutton addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:rightbutton] autorelease];
But it is not displaying any barbuttonitem. Instead if I use following code then barbutton item appears but problem is i cant set touch event with this code on barbuttonitem.
UIImageView *iconView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dashboard-icon.pn开发者_C百科g"]];
UIBarButtonItem *icon = [[UIBarButtonItem alloc] initWithCustomView:iconView];
self.navigationItem.leftBarButtonItem=icon;
[icon release];
[iconView release];
my guess is, that you add the UIBarButtonItem
to the wrong object!
you need to add it, to the rootViewController (instead to the UINavigationController
, as you probably did)
YourRootViewController *theRootController = [[YourRootViewController alloc] init];
UINavigationController* navContainer = [[UINavigationController alloc] initWithRootViewController:theRootController];
UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
[rightbutton setBackgroundImage:[UIImage imageNamed:@"share-icon.png"] forState:UIControlStateNormal];
[rightbutton addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
theRootController.navigationItem.rightBarButtonItem = rightbutton;
[navContainer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentModalViewController:navContainer animated:YES];
Don't forget to set tintColor on the UIBarButtonItem if you are using a white navigation bar. My buttons were there but invisible.
Have you tried to set an appropriate frame for the rightbutton
? e.g. rightbutton.frame = (CGRect){CGPointZero, image.size};
Also note:
On iOS 4 and later, the name of the file is not required to specify the filename extension. Prior to iOS 4, you must specify the filename extension.
Using swift 3.0 iOS 10.0
let customButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(yeah)) customButton.width = 100.0 navigationItem.rightBarButtonItem = customButton
func yeah(sender: UIBarButtonItem) { print("Yo Your the man/woman") }
I've had this problem when I set rightBardButtonItems for a child rather than rootmost viewcontroller
view controller always have navigationitem but that does not necessarily mean it has a navbar to show it in
精彩评论