Skip to content

Instantly share code, notes, and snippets.

@HamGuy
Last active October 10, 2021 01:05
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HamGuy/a099058e674b573ffe433132f7b5651e to your computer and use it in GitHub Desktop.
Save HamGuy/a099058e674b573ffe433132f7b5651e to your computer and use it in GitHub Desktop.
extension allows to handle UINavigationViewController's 'Back' button action, migrate from https://github.com/onegray/UIViewController-BackButtonHandler
//
// UINavigationBarBackButtonHandler.swift
// Demo
//
// Created by HamGuy on 20/04/2017.
// Copyright © 2017 hamguy.net. All rights reserved.
//
import Foundation
/// Handle UINavigationBar's 'Back' button action
protocol UINavigationBarBackButtonHandler {
/// Should block the 'Back' button action
///
/// - Returns: true - dot block,false - block
func shouldPopOnBackButton() -> Bool
}
extension UIViewController: UINavigationBarBackButtonHandler {
//Do not block the "Back" button action by default, otherwise, override this function in the specified viewcontroller
func shouldPopOnBackButton() -> Bool {
return true
}
}
extension UINavigationController: UINavigationBarDelegate {
public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool{
guard let items = navigationBar.items else {
return false
}
if viewControllers.count < items.count {
return true
}
var shouldPop = true
if let vc = topViewController, vc.responds(to: #selector(UIViewController.shouldPopOnBackButton)){
shouldPop = vc.shouldPopOnBackButton()
}
if shouldPop{
DispatchQueue.main.async {
self.popViewController(animated: true)
}
}else{
for aView in navigationBar.subviews{
if aView.alpha > 0 && aView.alpha < 1{
aView.alpha = 1.0
}
}
}
return false
}
}
/// Use age
class SomeController: UIViewController{
/**
......
do something
*/
override func shouldPopOnBackButton() -> Bool {
/**
do something
return false/true
*/
}
// Handle the pop gesture
override func willMove(toParentViewController parent: UIViewController?) {
if parent == nil { // When the user swipe to back, the parent is nil
do something
return
}
super.willMove(toParentViewController: parent)
}
}
@maulikshah09
Copy link

not working ...

@rpolenthon
Copy link

not working ...

Yep!

@syedrazackimran
Copy link

not working ...

roger that. for me also it's not working. kindly do needful.

@maulikshah09
Copy link

I used objective c code it's working fine....

@shxlxa
Copy link

shxlxa commented Jan 22, 2021

not working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment