Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add UINavigationBar programmatically with a Done button

So I have a modal view and want to add a UINavigationBar programmatically with a Done button to dismiss this view when the user finishes reading the content.

Any ideas on how to do this and if it's possible purely without using the interface builder?

like image 396
iPwnTech Avatar asked Jan 27 '13 07:01

iPwnTech


3 Answers

I am sorry that nobody here actually read your question... here is the code you are looking for:

UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
navBar.backgroundColor = [UIColor whiteColor];

UINavigationItem *navItem = [[UINavigationItem alloc] init];
navItem.title = @"Navigation Bar title here";

UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Left" style:UIBarButtonItemStylePlain target:self action:@selector(yourMethod:)];
navItem.leftBarButtonItem = leftButton;

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Post" style:UIBarButtonItemStylePlain target:self action:@selector(yourOtherMethod:)];
navItem.rightBarButtonItem = rightButton;

navBar.items = @[ navItem ];

[self.view addSubview:navBar];

I hope this helps, good luck :)

Add this code to your viewDidLoad method and everything will construct itself. Mind you, replace the selectors with your own method signatures-

Happy coding

like image 183
codeRefiner Avatar answered Nov 01 '22 11:11

codeRefiner


It is definitely possible.

Probably the easiest way is to embed the UIViewController your are presenting modally into a UINavigationViewController and then add the Done button, doing something like

UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] 
                            initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                            target:self 
                            action:@selector(dismiss)];
self.navigationItem.rightBarButtonItem = doneButton;

and implement a dismiss method like follows

- (void)dismiss {
    [self.presentingViewController dismissViewControllerAnimated:YES 
                                   completion:nil];
}
like image 27
Gabriele Petronella Avatar answered Nov 01 '22 12:11

Gabriele Petronella


//add done button to navigation bar
UIBarButtonItem *doneBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(userPressedDone)];
self.navigationItem.rightBarButtonItem = doneBarButtonItem;

Then have a method like this somewhere in your view controller

-(void)userPressedDone {
    // Action For Done Button Tapped
}
like image 32
iPatel Avatar answered Nov 01 '22 10:11

iPatel