如何向我的 UINavigationBar 添加后退按钮?
How do I add a back button to my UINavigationBar?
用户通过推送转场从上一个用户到达此 viewController,因此我希望 UINavigationBar
中有一个后退按钮以允许他们 return。
通常情况下,如果我右键单击 Storyboard 中的 viewController 并选择 Embed in
> Navigation Controller
,此后退按钮会默认出现,但这样做会导致崩溃,我更喜欢以编程方式做事,所以我决定在 viewDidLoad
中这样做:
// Nav bar
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
// Back Button
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:self action:@selector(Back)];
self.navigationItem.leftBarButtonItem = backButton;
[self.view addSubview:navbar];
这成功地在顶部添加了一个导航栏,但没有按预期添加后退按钮。我已经尝试了 here, , and here 给出的解决方案,但是 none 已经解决了问题。
您构建了一个 UINavigationBar
和一个 UIBarButtonItem
,但从未将两者连接起来。
UINavigationController
为您管理一个 UINavigationBar
并将其 topItem
设置为导航堆栈中最顶层视图控制器的 navigationItem
。如果您需要构建自己的导航栏,那么您需要自己管理它的项目堆栈。看看 UINavigationBar
的 - pushNavigationItem:animated:
方法。
但是鉴于您似乎想要 UINavigationController
的外观和功能,我不清楚为什么您要自己添加 UINavigationBar
视图而不是使用容器视图控制器。
用户通过推送转场从上一个用户到达此 viewController,因此我希望 UINavigationBar
中有一个后退按钮以允许他们 return。
通常情况下,如果我右键单击 Storyboard 中的 viewController 并选择 Embed in
> Navigation Controller
,此后退按钮会默认出现,但这样做会导致崩溃,我更喜欢以编程方式做事,所以我决定在 viewDidLoad
中这样做:
// Nav bar
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
// Back Button
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:self action:@selector(Back)];
self.navigationItem.leftBarButtonItem = backButton;
[self.view addSubview:navbar];
这成功地在顶部添加了一个导航栏,但没有按预期添加后退按钮。我已经尝试了 here,
您构建了一个 UINavigationBar
和一个 UIBarButtonItem
,但从未将两者连接起来。
UINavigationController
为您管理一个 UINavigationBar
并将其 topItem
设置为导航堆栈中最顶层视图控制器的 navigationItem
。如果您需要构建自己的导航栏,那么您需要自己管理它的项目堆栈。看看 UINavigationBar
的 - pushNavigationItem:animated:
方法。
但是鉴于您似乎想要 UINavigationController
的外观和功能,我不清楚为什么您要自己添加 UINavigationBar
视图而不是使用容器视图控制器。