温馨提示:本文翻译自stackoverflow.com,查看原文请点击:ios - Execute action when back bar button of UINavigationController is pressed
ios swift xcode uinavigationcontroller

ios - 当按下UINavigationController的后退按钮时执行操作

发布于 2020-03-27 11:49:39

UINavigationController按下a的后退按钮时,我需要执行一个操作(清空数组),而该按钮仍会导致ViewController堆栈中的前一个出现。我如何使用swift完成此操作? 在此处输入图片说明

查看更多

查看更多

提问者
StevenR
被浏览
178
6,422 2016-11-18 03:07

一种选择是实现自己的自定义后退按钮。您需要将以下代码添加到viewDidLoad方法:

- (void) viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = newBackButton;
}

- (void) back:(UIBarButtonItem *)sender {
    // Perform your custom actions
    // ...
    // Go back to the previous ViewController
    [self.navigationController popViewControllerAnimated:YES];
}

更新:

这是Swift的版本:

    override func viewDidLoad {
        super.viewDidLoad()
        self.navigationItem.hidesBackButton = true
        let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Bordered, target: self, action: "back:")
        self.navigationItem.leftBarButtonItem = newBackButton
    }

    func back(sender: UIBarButtonItem) {
        // Perform your custom actions
        // ...
        // Go back to the previous ViewController
        self.navigationController?.popViewControllerAnimated(true)
    }

更新2:

这是Swift 3的版本:

    override func viewDidLoad {
        super.viewDidLoad()
        self.navigationItem.hidesBackButton = true
        let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(YourViewController.back(sender:)))
        self.navigationItem.leftBarButtonItem = newBackButton
    }

    func back(sender: UIBarButtonItem) {
        // Perform your custom actions
        // ...
        // Go back to the previous ViewController
        _ = navigationController?.popViewController(animated: true)
    }