开发者

iOS - how to create a navigation bar item in view controller?

开发者 https://www.devze.com 2023-04-01 07:29 出处:网络
I have been trying to create a navigation bar back button. Here is my code :- UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithTitle:@\"Done\" style:UIBarButtonItemStyleBordered targe

I have been trying to create a navigation bar back button.

Here is my code :-

UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:nil]autorelease];
self.navigationItem.rightBarButtonItem = barButton;

But it isn't displaying anything on navigation bar.

I am using UIViewController, not an UINavigationController.

Is UINavigationController开发者_运维问答 is the only way to achieve this?

Any help would be really appreciated.

Any link to a good tutorial will be great.

Thanks.


Without the viewcontroller having a navigation controller (i.e viewController.navigationController != nil) you cannot add it in this manner.

One thing you can do is if it is being created by the nib is to just drag a bar button item into a navigation bar and link it via IBAction.


I'd recommend pushing this view controller out of a nvigationcontroller - you will get all those things for free:

UIViewController *vc = [[UIViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navCntrl1 = [[UINavigationController alloc] initWithRootViewController:vc];


If you have your view controller being created from a NIB file in Interface Builder, and the view controller's design surface has a navigation bar on it, the easiest way to do this would be to drag a bar button item from the objects inspector right onto the navigation bar's right side. You would then create an IBAction in your header and implementation that you would hook up to.


I achieve this inserting the button directly in the UINavigationBar:

[yourUINavBar insertSubview:yourButton atIndex:1];


UIViewController's -navigationItem method does only work together with UINavigationController or other UIViewController containments. You will have to get access to the UINavigationBar and set the item directly.


If you want to have a navigation bar, and have it work as you expect, create a UINavigationController using your UIViewController as the root view controller. Use that UINavigationController where you are using your UIViewController now.

Check out UINavigationController at developer.apple.com for more details.

0

精彩评论

暂无评论...
验证码 换一张
取 消