0

我正在尝试全局更改导航栏的正确项目。所以我创建了这样的父类:

@implementation ParentViewController
...
- (void)loadView {
    [super loadView];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"send"]];
    self.navigationController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:sendImageView];

}
...
@end

我有两个ViewController名为的类AB它们继承自ParentViewController. 他们俩都有

- (void)loadView {
     [super loadView];
}

A的第一个实例出来并执行

    B *vc = [[B alloc] init];
    [self.navigationController pushViewController:vc animated:YES];

问题是右栏按钮项仅出现在 A 上而不出现在 B 上。我认为loadView调用父类会解决问题,但事实并非如此。如何全局更改该按钮?

我没有使用xib。所以 loadView 总是被调用。

4

3 回答 3

1

loadView如果视图控制器具有关联的 XIB,则不会调用它,因为它将用于加载视图。

您可能需要考虑充当delegate处理UINavigationController这些东西并实施navigationController:willShowViewController:animated:. 然后你可以直接询问新viewController的来决定你是否应该做任何事情,如果需要,你可以改变它的navigationItem.

于 2013-09-22T11:53:12.820 回答
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;

于 2013-09-23T03:44:46.850 回答
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 中进一步设置它,这需要一些技巧(在这个答案中太多了)。

于 2014-03-15T05:35:06.910 回答