我在UIViewController中添加了一个导航栏。它仅从另一个UIViewController显示。我想要一个左侧后退按钮,其形状类似于箭头,就像普通的导航栏后退按钮一样。我似乎只能通过IB添加一个条形按钮。我猜测后退按钮需要以编程方式添加。关于我应该怎么做的任何建议?
目前,在RootController中,我通过简单地执行addSubView来推送另一个UIViewController(viewB)。在viewB中,我想显示导航栏。该应用程序是基于视图的,而不是基于导航控制器。
答案 0 :(得分:13)
如果您使用的是导航控制器:
MyViewController *_myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
[[self navigationController] pushViewController:_myViewController animated:YES];
UIBarButtonItem *_backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.backBarButtonItem = _backButton;
[_backButton release], _backButton = nil;
[_myViewController release], _myViewController = nil;
如果您没有使用导航控制器,请查看Three20 style组件以制作自定义栏按钮。
答案 1 :(得分:7)
我已经按照以下方式完成了
在viewDidLoad方法中我有这段代码:
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 41)];
navBar.delegate = self;
UINavigationItem *backItem = [[UINavigationItem alloc] initWithTitle:@"Back"];
[navBar pushNavigationItem:backItem animated:NO];
[backItem release];
UINavigationItem *topItem = [[UINavigationItem alloc] initWithTitle:@"Your Title"];
[navBar pushNavigationItem:topItem animated:NO];
topItem.leftBarButtonItem = nil;
[topItem release];
[self.view addSubview:navBar];
[navBar release];
然后在标头中添加符合UINavigationBarDelegate协议并以这种方式实现委托方法:
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
//if you want to dismiss the controller presented, you can do that here or the method btnBackClicked
return NO;
}
答案 2 :(得分:0)
解决此问题的另一种方法是设置导航栏的items属性,而不是将条形项连续推入导航栏堆栈:
//Define myFrame based on your needs
let navigationBar = UINavigationBar(frame: myFrame)
let backItem = UINavigationItem(title: "Back")
let topItem = UINavigationItem(title: "My Title")
navigationBar.setItems([backItem,topItem], animated: false)