Reputation: 2044
I'm writing a simple app in iOS using Xcode, I'm trying to load another ViewController
as a modal. The origin HomeScreenViewController
(inherits from UIViewController
) where I'm loading the modal is originated with the project's Storyboard.
Then, as a response to a button pressed event, I'm loading this modal like this:
-(IBAction)onAddButtonPressed:(UIButton *)sender {
MyAnotherViewController *vc = [[MyAnotherViewController alloc] init];
[self presentViewController:vc animated:YES completion:nil];
}
The class MyAnotherViewController
is not represented in the Storyborad since its a simple class to show a navigation bar and a text field. The code is (partial code, the rest is Xcode auto-generated methods):
@implementation MyAnotherViewController
- (void)viewDidLoad {
[self.navigationItem setTitle:@"Example"];
[self.view addSubview:[[UITextView alloc]initWithFrame:self.view.bounds]];
}
@end
The problem is (also can be seen in the attached image) that the navigationItem
is not shown for some reason.
I also validated that self.navigationItem
is not nil
and it is not. Even more, I can see in debug mode that the title is actually set to "Example".
Your help is well appreciated,
Cheers...
Upvotes: 0
Views: 2350
Reputation: 2567
If your MyAnotherViewController
is not a subclass of UINavigationController
, or if you have not manually add an UINavigationItem
, UIViewController
cannot show a navigation item. Maybe you can try to wrap the MyAnotherViewController
with an UINavigationController
.
// Assume you have adopted ARC
-(IBAction)onAddButtonPressed:(UIButton *)sender {
MyAnotherViewController *vc = [[MyAnotherViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
[self presentViewController:nav animated:YES completion:nil];
}
And in your -viewDidLoad
of MyAnotherViewController
, you just need to do this:
-(void)viewDidLoad {
self.title = @"Example";
/*
* Your other code
*/
}
Upvotes: 0
Reputation: 11724
The UINavigationItem
property of a UIViewController is only used when the ViewController is inside a UINavigationController
, so :
-(IBAction)onAddButtonPressed:(UIButton *)sender {
MyAnotherViewController *vc = [[MyAnotherViewController alloc] init];
UINavigationController *navCtl = [[UINavigationController alloc] initWithRootController:vc];
[self presentViewController:navCtl animated:YES completion:nil];
}
Upvotes: 2