无法向导航控制器iOS Xcode的后退按钮添加操作

时间:2014-12-11 06:29:11

标签: ios xcode uibarbuttonitem

-(void)viewDidAppear:(BOOL)animated
{
    UIBarButtonItem *navigationBarbackButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(backToRootView:)];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.backBarButtonItem = navigationBarbackButton;
}


-(void)backToRootView:(UIBarButtonItem *)sender
{

    [self.navigationController popToRootViewControllerAnimated:YES];
}

1 个答案:

答案 0 :(得分:0)

这里的矛盾是您要将操作事件设置为backBarButtonItem并将其设置为hidden。所以它现在不可见。

viewDidAppear()方法中删除以下行:

self.navigationItem.hidesBackButton = YES;

为视图生命周期方法调用super类方法也是很好的编程。

如此更新的方法将是:

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    UIBarButtonItem *navigationBarbackButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(backToRootView:)];
    self.navigationItem.backBarButtonItem = navigationBarbackButton;
}

修改

backBarButtonItem有弹出控制器的默认操作,您不需要为此添加操作事件。我不确定您是否担心使用后退按钮,但如果您尝试自定义左按钮项目,则必须遵循以下代码:

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    UIBarButtonItem *navigationBarbackButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(backToRootView:)];
    self.navigationItem.leftBarButtonItem = navigationBarbackButton;
}


-(void)backToRootView:(UIBarButtonItem *)sender
{

    [self.navigationController popToRootViewControllerAnimated:YES];
}