O. Boujaouane
O. Boujaouane

Reputation: 285

Extension of UIBarButtonItem when touchesBegan

I am working actually on management of connection with a ReachabilityManager class.

I have created a toast which show when connection is lost and recovered. I also created two extensions (UIButton and UISwitch) and on it I override func touchesBegan to check and play action of button/switch or to show the toast with error message only (and don't play selector of button/switch).

Here my UIButton extension to understand:

extension UIButton {
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if ReachabilityManager.shared.reachability.connection == .none {
            ReachabilityManager.shared.customConnectionToast(ToastStyle.connectionLost.applyStyle(),
                                  description: NSLocalizedString("no_connection_error_message", comment: ""))
        } else {
            sendActions(for: UIControlEvents.allTouchEvents)
        }
    }
}

I need now to create the same extension for UIBarButtonItem but the problem is there is no touchesBegan action for this object and I don't know how to make something similar to UIbutton and UISwitch extensions. Another information on why I want that is that I can't refactor all barbutton items of the app (it will take me 2 weeks). It's for that I have to find a way with extension or something else but absolutely a generic solution.

If anyone has any idea I would be grateful.

In advance thank you.

Kind Regards,

Upvotes: 1

Views: 213

Answers (1)

Glenn Posadas
Glenn Posadas

Reputation: 13300

One quick solution: Use UIButton and make that a UIBarButtonItem, then you can use your category above you posted (extension of UIButton) to your new button acting as a barButtonItem.

Like so:

internal lazy var button_Close: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(.close, for: .normal)
        button.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -30, bottom: 0, right: 0)
        button.addTarget(self, action: #selector(back(_:)), for: .touchUpInside)
        return button
    }()

Make it a barButton item:

override func viewDidLoad() {
    super.viewDidLoad()

    let barButton = UIBarButtonItem(customView: self.button_Close)
    self.button_Close.frame = CGRect(x: 0, y: 0, width: 55.0, height: 44.0)
    let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
    if #available(iOS 11.0, *) {
        negativeSpacer.width = -30
    }
    self.navigationItem.leftBarButtonItems = [negativeSpacer, barButton]
}

I hope this helps!

Upvotes: 1

Related Questions