4

Can I add a UIBarButtonItem completely free?

 2 years ago
source link: https://www.codesd.com/item/can-i-add-a-uibarbuttonitem-completely-free.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Can I add a UIBarButtonItem completely free?

advertisements

I created a nav bar and a label programmatically in my view controller. Now I want to add a "done" button but cant seem 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];




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK