Add UINavigationBar programmatically with a Done button

iPwnTech picture iPwnTech · Jan 27, 2013 · Viewed 15.2k times · Source

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?

Answer

codeRefiner picture codeRefiner · Oct 15, 2013

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