简体   繁体   English

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

[英]Not able to add action to back button of navigation controller iOS Xcode

-(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];
}

Here contradiction is that you are setting action event to backBarButtonItem and also set it to hidden . 这里的矛盾之处在于,您backBarButtonItem动作事件设置为backBarButtonItem ,也将其设置为hidden So it is not visible right now. 因此,目前尚不可见。

Remove below line from viewDidAppear() method: viewDidAppear()方法中删除以下行:

self.navigationItem.hidesBackButton = YES;

Also it is good programming to call super class method for view life cycle methods. 调用super类方法作为视图生命周期方法也是一种很好的编程方法。

So updated method will be: 因此更新的方法将是:

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

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

Edit: 编辑:

backBarButtonItem has default action to pop controller, you don't need to add an action event for that. backBarButtonItem对弹出控制器具有默认操作,您无需为此添加操作事件。 I'm not sure about your concern to use back button but if you are trying customise left button item then must follow this code: 我不确定您是否担心使用后退按钮,但是如果您尝试自定义左按钮项,则必须遵循以下代码:

-(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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM