我需要执行一个动作(清空一个数组),当UINavigationController的后退按钮被按下,而按钮仍然导致堆栈上的前一个ViewController出现。我如何使用swift来实现这一点?


当前回答

在Swift 5和Xcode 10.2中

请不要添加自定义栏按钮项,使用默认行为。

不需要viewWillDisappear,不需要自定义BarButtonItem等…

最好是检测VC何时从其父对象中移除。

使用这两个函数中的任意一个

override func willMove(toParent parent: UIViewController?) {
    super.willMove(toParent: parent)
    if parent == nil {
        callStatusDelegate?.backButtonClicked()//Here write your code
    }
}

override func didMove(toParent parent: UIViewController?) {
    super.didMove(toParent: parent)
    if parent == nil {
        callStatusDelegate?.backButtonClicked()//Here write your code
    }
}

如果你想停止返回按钮的默认行为,然后添加自定义BarButtonItem。

其他回答

override func willMove(toParent parent: UIViewController?)
{
    super.willMove(toParent: parent)
    if parent == nil
    {
        print("This VC is 'will' be popped. i.e. the back button was pressed.")
    }
}
    override public func viewDidLoad() {
         super.viewDidLoad()
         self.navigationController?.navigationBar.topItem?.title = GlobalVariables.selectedMainIconName
         let image = UIImage(named: "back-btn")

         image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(Current[enter image description here][1]ViewController.back) )
    }

    func back() {
      self.navigationController?.popToViewController( self.navigationController!.viewControllers[ self.navigationController!.viewControllers.count - 2 ], animated: true)
    }

NO

override func willMove(父控件:UIViewController?) {}

即使你在segue到覆盖这个方法的视图控制器,这个也会被调用。其中,检查parent是否为nil或not不是确保移动回正确的UIViewController的精确方法。为了准确地确定UINavigationController是否正确地导航回呈现当前的UIViewController,你将需要遵守UINavigationControllerDelegate协议。

YES

注意:MyViewController只是你想要检测返回的UIViewController的名称。

1)在你的文件顶部添加UINavigationControllerDelegate。

class MyViewController: UIViewController, UINavigationControllerDelegate {

2)添加一个属性到你的类,它将跟踪你正在segue的UIViewController。

class MyViewController: UIViewController, UINavigationControllerDelegate {

var previousViewController:UIViewController

3)在MyViewController的viewDidLoad方法中为你的UINavigationController分配self作为委托。

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.delegate = self
}

3)在你segue之前,将之前的UIViewController分配为这个属性。

// In previous UIViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "YourSegueID" {
        if let nextViewController = segue.destination as? MyViewController {
            nextViewController.previousViewController = self
        }
    }
}

4)并遵循UINavigationControllerDelegate的MyViewController中的一个方法

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    if viewController == self.previousViewController {
        // You are going back
    }
}

如果你想有后退按钮和后退箭头,你可以使用下面的图片和代码

backArrow.png backArrow@2x.png backArrow@3x.png

override func viewDidLoad() {
    super.viewDidLoad()
    let customBackButton = UIBarButtonItem(image: UIImage(named: "backArrow") , style: .plain, target: self, action: #selector(backAction(sender:)))
    customBackButton.imageInsets = UIEdgeInsets(top: 2, left: -8, bottom: 0, right: 0)
    navigationItem.leftBarButtonItem = customBackButton
}

func backAction(sender: UIBarButtonItem) {
    // custom actions here
    navigationController?.popViewController(animated: true)
}

一种选择是实现您自己的自定义后退按钮。你需要添加以下代码到你的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
        }

       @objc 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
        }

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