如何在 swift 上按下后退按钮时隐藏上一页的弹出视图

How to hide pop up view on previous page when pressing back button on swift

我有这样的流量页:

设置页面 --> 输入密码 --> 转到第 X 页

因此在设置页面中,为了转到第 X 页,我必须使用弹出视图输入密码。 当我在第 X 页并且我想返回上一页时,我去输入密码弹出视图,而不是设置页面。 如何跳过该页面?

我的弹出视图代码是这样的:

let btn = storyboard?.instantiateViewController(withIdentifier: "PopUpView") as! PopUpView
        addChild(btn)
        btn.view.frame = view.frame
        view.addSubview(btn.view)
        btn.didMove(toParent: self)

我是新来的,任何帮助将不胜感激。

谢谢。

使用设置视图控制器的当前函数打开弹出窗口。

//In your settings view

func openPopup() {
    let btn = storyboard?.instantiateViewController(withIdentifier: "PopUpView") as! PopUpView
    self.present(btn, animated: true, completion: nil)
}

当用户点击确定时,在您的弹出视图上调用 dismiss 并使用闭包启动页面打开到 X

//In your 'PopUpView' On the OK button action of your popup

func didTouchOk() {
    self.dismiss(animated: true) { [weak self] in
        guard let self = self else { return }
            
        //Put your open page X code here
        let XView = storyboard?.instantiateViewController(withIdentifier: "XViewController") as! XView
        self.present(XView, animated: true, completion: nil)
    }
}

如果您使用的是导航控制器:

在 PopUpView 中声明一个协议

protocol popupDelegate: class {
    func userDidTouchOkInPopup()
}

在 PopUpView 中创建一个弱变量

weak var delegate: popupDelegate? = nil

在您的设置中 viewcontroller:

在推送之前将委托分配给弹出窗口

func openPopup() {
    let btn = storyboard?.instantiateViewController(withIdentifier: 
    "PopUpView") as! PopUpView
    btn.delegate = self
    self.navigationController?.pushViewController(btn, animated: true)
}

为此协议实施扩展

extension SettingsViewController:  popupDelegate {

    func userDidTouchOkInPopup() {
        self.navigationController?.popViewController(animated: true)
        let XView = storyboard?.instantiateViewController(withIdentifier: 
        "XViewController") as! XView
        self.navigationController?.pushViewController(XView, animated: true)

    }

}

修改 PopUpView 中的确定操作

//In your 'PopUpView' On the OK button action of your popup

func didTouchOk() {
    self.delegate?.userDidTouchOkInPopup()
}

如果您在 navigationController 层次结构中,请使用 navigationController.popToViewController 转到特定的 ViewController。 在 ViewDidLoad 中,隐藏当前的后退按钮并创建一个新的后退按钮并与其关联操作。

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

里面backButtonFunction,可以放代码

@objc func backButtonFunction(){
  if let navController = self.navigationController {                                
    for controller in navController.viewControllers {
       if controller is SettingsViewController { // Change name of ViewController accordingly
          navController.popToViewController(controller, animated:true)
        break
     }
  }
}
}