尝试以编程方式设置导航栏,但我的标题未显示在导航栏中。关于正在发生的事情有什么想法吗?
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
navbar.topItem.title = @"My accounts";
[self.view addSubview:navbar];
最佳答案
这里的问题是您对 UINavigationBar
的使用。
阅读 UINavigationController
programming here. 的文档
您不应该创建自己的 UINavigationBar
并将其作为 subview 添加到 View Controller 的 View 中。
正确的做法是创建一个 UINavigationController
并将您的 View Controller 添加到它的堆栈中。
所以像这样:
CustomViewController *myViewController = ...// whatever initialization you do
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myViewController];
每个 View Controller 都有自己的 UINavigationItem
,当该 View Controller 位于堆栈顶部时,导航 Controller 使用它来设置导航栏的 View 。
因此,在您的 CustomViewController.m
中,可能在 init
方法或 viewDidLoad
中,
您可以通过执行以下操作来设置导航项:
self.navigationItem.title = @"whatever";
self.navigationItem.rightBarButtonItem = ...// create a UIBarButtonItem and set it here if you want a button on the right side of the navigation bar
所以再说一次,您不要直接触摸导航栏或将其添加到您的 View 层次结构中。 UINavigationController
会为您处理所有这些。
关于ios - UINavigationBar 在 iOS 中不显示标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24294576/