覆盖导航堆栈中的后退按钮,同时保持默认后退按钮的外观?

Pin*_*ntu 15 uinavigationcontroller uinavigation

如何覆盖后退按钮仅一个视图(不用于存在于不同视图的所有后退按钮),以使得在背面点击按钮,根视图控制器被示出.

Mik*_*etz 32

您需要替换后退按钮并关联操作处理程序:

- (void)viewDidLoad {
    [super viewDidLoad];

    // change the back button to cancel and add an event handler
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@”back”
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(handleBack:)];

    self.navigationItem.leftBarButtonItem = backButton;
}

- (void)handleBack:(id)sender {
    // pop to root view controller
    [self.navigationController popToRootViewControllerAnimated:YES];
}
Run Code Online (Sandbox Code Playgroud)

  • Apple准则不会"允许"更改UI元素的预期行为,例如后退按钮.当iOS用户看到"正常"后退按钮样式时,她期望正常的后退按钮行为.如果您想更改此行为,则应实现"普通"样式按钮. (7认同)
  • 嗨,谢谢你的回答,但是我想保留后退按钮的样式,而不是创建一个新的按钮. (6认同)
  • 至于我,如果用户推回,并且还没有保存当前屏幕上的什么,我想显示一个弹出窗口"你确定你想要回去而不保存吗?" 我相信这是可以接受的 (4认同)

Sar*_*glt 13

找到了一个保留后退按钮风格的解决方案.将以下方法添加到视图控制器.

-(void) overrideBack{

    UIButton *transparentButton = [[UIButton alloc] init];
    [transparentButton setFrame:CGRectMake(0,0, 50, 40)];
    [transparentButton setBackgroundColor:[UIColor clearColor]];
    [transparentButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:transparentButton];


}
Run Code Online (Sandbox Code Playgroud)

现在根据需要提供以下方法中的功能:

-(void)backAction:(UIBarButtonItem *)sender {
    //Your functionality
}
Run Code Online (Sandbox Code Playgroud)

它所做的只是用透明按钮覆盖后退按钮;)

  • @Brave这不是一个好的解决方案.这是一个hacky解决方案. (5认同)

val*_*alR 6

这是旧的,但正确的答案是:

您最好用rootVC和新VC替换整个堆栈,而不是将ViewController推到所有其他控件之上.

不:

self.navigationController?.pushViewController(myVc, animated: true)
Run Code Online (Sandbox Code Playgroud)

但:

let vcStack = self.navigationController?.viewControllers
self.navigationController?.setViewControllers([vcStack![0],myVc], animated: true)
Run Code Online (Sandbox Code Playgroud)

就像那样,在背面它只是popToRoot,因为它是堆栈中的前一个viewController


Pav*_*vic 6

我有类似的问题,我成功地使用了Sarasranglt给出的答案.这是SWIFT版本.

    override func viewDidLoad() {
       let transparentButton = UIButton()
       transparentButton.frame = CGRectMake(0, 0, 50, 40)
       transparentButton.backgroundColor = UIColor.orangeColor()
       transparentButton.addTarget(self, action:"backAction:", forControlEvents:.TouchUpInside)
       self.navigationController?.navigationBar.addSubview(transparentButton)
    }
Run Code Online (Sandbox Code Playgroud)

功能是

 func backAction(sender:UIButton) {
     // Some sction
 }
Run Code Online (Sandbox Code Playgroud)