iPwnTech
iPwnTech

Reputation: 555

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?

Upvotes: 11

Views: 15399

Answers (3)

codeRefiner
codeRefiner

Reputation: 513

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

Upvotes: 48

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

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];
}

Upvotes: 7

iPatel
iPatel

Reputation: 47059

//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
}

Upvotes: 3

Related Questions