Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active January 15, 2019 00:22
Show Gist options
  • Save KentarouKanno/da35659e5b15fe983bf4ad634d891d91 to your computer and use it in GitHub Desktop.
Save KentarouKanno/da35659e5b15fe983bf4ad634d891d91 to your computer and use it in GitHub Desktop.
  • extension
class NavigationCloseButton: UIButton {
    var actionHandler: (() -> Void)?
}


extension UIViewController {

    func createNavigationClose(actionHandler: (() -> Void)? = nil) {
        let button = NavigationCloseButton(type: .custom)
        button.frame = CGRect(0, 0, 44, 35)
        button.actionHandler = actionHandler
        button.setImage(UIImage(named: "CloseImage"), for: .normal)
        button.addTarget(self, action: #selector(naviClose(_:)), for: .touchUpInside)
        let backButtonItem:UIBarButtonItem =  UIBarButtonItem(customView: button)
        navigationItem.leftBarButtonItem = backButtonItem
    }

    @objc func naviClose(_ sender: NavigationCloseButton) {
        sender.actionHandler?()
    }
}
  • Usage
class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()

        createNavigationClose { [weak self] in
            guard let self = self else { return }
            
            self.dismiss(animated: true)
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment