can I add a UIBarButtonItem completely IB free?
I created a nav bar and a label programmatically in my view controller. Now I want to add a "done" button but cant s开发者_StackOverfloweem to find a way without using IB....is there any way to do that?
Here is my view controller's viewDidLoad:
//Adding navBar programmatically
CGFloat width = self.view.frame.size.width;
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0,0,width,52)];
navBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.view addSubview:navBar];
//Adding label to navBar programmatically
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,2,width-20,14)];
label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
label.text = @"TITLE";
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont systemFontOfSize:22];
label.shadowOffset = CGSizeMake(1,1);
label.textColor = [UIColor whiteColor];
label.textAlignment = UITextAlignmentCenter;
[navBar addSubview:label];
//Adding back button to navBar programmatically
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(dismissView:)];
self.navigationItem.leftBarButtonItem = rightButton;
Last part obviously doesnt work...
Thanks for any help!
Why are you not using a UIToolBar
instead?
To add buttons to a UINavigationBar
, you need to create a UINavigationItem
. If you're using UINavigationBar
as part of UINavigationController
(as is the common case), this is done automatically, as a standalone view, you have to do this yourself.
UINavigationItem *item = [[[UINavigationItem alloc] initWithTitle:@""] autorelease];
item.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismissView:)] autorelease];
[navBar setItems:[NSArray arrayWithObject:item] animated:NO];
The navigationItem is only used when you push a viewcontroller in a navigationcontroller
in your case you need to use
-pushNavigationItem:animated:
on the UINavigationBar
Check the docs for more details:
http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UINavigationBar_Class/Reference/UINavigationBar.html
精彩评论