iOS左侧带有自定义视图的UIBarButtonItem使默认后退按钮显示在下方

时间:2014-11-28 16:00:23

标签: ios uinavigationcontroller uibarbuttonitem

我有以下设置:

CustomNavigationController.h:

@interface CustomNavigationController : UINavigationController

@end

CustomNavigationController.m:

@interface CustomNavigationController () <UINavigationControllerDelegate>

@property (nonatomic, strong) UIBarButtonItem *backBarButtonItem;
@property (nonatomic, strong) UIBarButtonItem *burgerBarButtonItem;

@end

@implementation CustomNavigationController

-(id)initWithCoder:(NSCoder *)aDecoder{

    self = [super initWithCoder:aDecoder];
    if(self){

        self.delegate = self;

        UIView *customView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        [customView setBackgroundColor:[UIColor redColor]];

        UIView *anotherCustomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        [anotherCustomView setBackgroundColor:[UIColor redColor]];

        self.backBarButtonItem   = [[UIBarButtonItem alloc]initWithCustomView:customView];
        self.burgerBarButtonItem   = [[UIBarButtonItem alloc]initWithCustomView:anotherCustomView];

    }

    return self;
}


-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{

    [viewController.navigationItem setLeftBarButtonItems:@[self.backBarButtonItem, self.burgerBarButtonItem]];

    viewController.navigationItem.title = @"My custom title";

}

@end

我正在使用故事板初始化它。根视图控制器只有一个按钮,可以将其他视图控制器推送到navigationControllers&#39;叠加。

显示了2个自定义UIBarButtonItem视图,其行为与预期一致。但是,当我按下一个新的视图控制器时,最左边的barButtonItem下面会出现一个神秘的后退按钮。这似乎只有在我添加了自定义标题时才会发生。如果我删除了行viewController.navigationItem.title = @"My custom title";,那么它正在按预期工作。

根视图控制器:

enter image description here

任何后续视图控制器:

enter image description here

我假设因为我添加了一个自定义的leftBarItems属性,它将覆盖默认的后退按钮,但如果我要添加一个标题 - 似乎不是这种情况。此外,只有在我使用UIBarButtonItem初始化initWithCustomView时才会出现这种情况,如果我使用的是标准UIBarButtonIteminitWithImage则可以正常使用。

如何确保后退按钮不显示?在iOS 7,iOS 8上测试,使用ARC和自动布局。

修改

当我做navigationItem.hidesBackButton = YES时;无论是在视图控制器的viewDidLoad中还是在willShowViewController中,都会发生这种情况:(注意点 - 它们会出现并淡出)

enter image description here

1 个答案:

答案 0 :(得分:0)

添加

viewController.navigationItem.hidesBackButton = YES;

到你的

-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated