我正在尝试全局更改导航栏的正确项目。所以我创建了这样的父类:
@implementation ParentViewController
...
- (void)loadView {
[super loadView];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"send"]];
self.navigationController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:sendImageView];
}
...
@end
我有两个名为ViewController
和A
的{{1}}个类继承自B
。他们俩都有
ParentViewController
A的第一个实例出来并执行
- (void)loadView {
[super loadView];
}
问题是右栏按钮项目仅出现在A上,但不出现在B.我认为被调用的父类 B *vc = [[B alloc] init];
[self.navigationController pushViewController:vc animated:YES];
会起作用但不是。如何全局更改该按钮?
我没有使用xib。所以loadView总是被调用。
答案 0 :(得分:1)
loadView
,因为它将用于加载视图。
您可能需要考虑充当delegate
UINavigationController
来处理这些问题并实施navigationController:willShowViewController:animated:
。然后,您可以直接询问新viewController
以决定是否应该执行任何操作,如果需要,您可以更改其navigationItem
。
答案 1 :(得分:0)
我想我找到了解决问题的方法。它将右侧项目更改为普通图像,并将左侧项目设置为后退按钮,标题为“后退”。
@implementation ParentViewController
- (void)loadView {
[super loadView];
UIImageView *sendImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"send"]];
sendImageView.frame = CGRectMake(0, 0, 44, 44);
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:sendImageView];
//don't need the original back button
self.navigationItem.hidesBackButton = YES;
self.navigationItem.leftBarButtonItem = nil;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
[self.navigationItem.leftBarButtonItem configureFlatButtonWithColor:[UIColor whiteColor] highlightedColor:[UIColor lightGrayColor] cornerRadius:5];
self.navigationItem.leftBarButtonItem.title = @"Back";
[self.navigationItem.leftBarButtonItem
setTitleTextAttributes:@{
UITextAttributeTextColor: [UIColor colorFromHexCode:@"53a4db"],
UITextAttributeTextShadowColor: [UIColor clearColor],
UITextAttributeFont: [UIFont fontWithName:@"ChalkboardSE-Bold" size:15]
} forState:UIControlStateNormal];
}
-(void)back {
[self.navigationController popToRootViewControllerAnimated:YES];
}
@end
因此,如果子课不需要后退按钮,它可以self.navigationItem.leftBarButtonItem = nil;
答案 2 :(得分:0)
我最近撰写了一篇关于此问题的博文:http://www.codebestowed.com/ios-shared-barbuttonitems/
基本思想是子类UINavigationController,给它一个BarButtonItem属性(下面代码中的self.myButton)并添加类似于的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
self.delegate = self;
}
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (!viewController.navigationItem.rightBarButtonItem) {
viewController.navigationItem.rightBarButtonItem = self.myButton;
}
}
对于那些感兴趣的人,博客文章详细说明了如何在InterfaceBuilder中进一步设置这一点,这需要一点点破解(在这个答案中太多了)。