如何完全覆盖导航栏的后退按钮操作?

时间:2019-08-05 21:56:34

标签: ios swift xcode uinavigationbar uinavigationitem

基本上我的问题是我试图创建一个抽屉,因为iOS / Swift似乎没有为此的本机对象。由于我不记得的原因,我决定为此使用导航控制器,以为我可以覆盖后退按钮及其将导航栏变成抽屉的动作。虽然我成功地将“后退”按钮的图像/文本更改为看起来像“汉堡”(抽屉图标),但我无法弄清楚如何成功地阻止该按钮将我们带回,而只是将其打开/关上我的抽屉。

任何建议,包括采用完全不同的方法来创建它的建议。

以下是页面的控制器,该页面具有我要覆盖的后退按钮。您可以在viewDidLoad()中看到我称为prepareDrawerPage()的信息,这是我在另一个文件中拥有的帮助程序。这个定义也可以在下面看到。

class CreateListingController: UIViewController {
    let DRAWER_OPEN = CGFloat(0)
    var DRAWER_CLOSED: CGFloat = 0  // -1 * width of drawer

    @IBOutlet var navItem: UINavigationItem!
    @IBOutlet var drawerView: UIView!
    @IBOutlet var drawerViewLead: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        DRAWER_CLOSED = UIScreen.main.bounds.width * -1 * drawerViewLead.multiplier
        drawerViewLead.constant = DRAWER_CLOSED
        prepareDrawerPage(controller: self, title: "PBX - Create a Listing")
    }


    @IBAction func flipMenu(_ sender: UIBarButtonItem) {
        if (drawerViewLead.constant == DRAWER_OPEN){
            drawerViewLead.constant = DRAWER_CLOSED
            UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseOut, animations: {
                self.view.layoutIfNeeded()
            })
        } else {
            drawerViewLead.constant = DRAWER_OPEN
            UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseIn, animations: {
                self.view.layoutIfNeeded()
            })
        }
    }

}

prepareDrawerPage():

func prepareDrawerPage(controller: UIViewController, title: String) {
    let blank = UIImage()
    controller.navigationController?.navigationBar.backIndicatorImage = blank
    controller.navigationController?.navigationBar.backIndicatorTransitionMaskImage = blank
    controller.title = title
}

以上方法在主页上还可以,我们尚未使用导航栏。但是,一旦我们单击了“创建列表”页面,尽管在BarButtonItem(后退按钮)和CreateListingController(flipMenu函数)之间链接了一个动作,但单击后该按钮仍会将我们带回家。

1 个答案:

答案 0 :(得分:0)

您可以在导航栏上添加自定义按钮。

override func viewDidLoad() {
    ...
    self.navigationItem.hidesBackButton = true
    let newBackButton = UIBarButtonItem(image: YourImage, style: .plain, target: self, action: #selector(back(sender:)))
    self.navigationItem.leftBarButtonItem = newBackButton
    ...
}

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