Abhishek Mitra Abhishek Mitra - 13 days ago 9
iOS Question

UIButton Extension For UIBarButtonItem

I'm writing an extension by taking a swift file and did codes in following way:

import Foundation
import UIKit

extension UIButton{

func backButtonTarget(_ target: Any, action: Selector) -> UIBarButtonItem {
let backButton = UIButton(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(12), height: CGFloat(20)))
backButton.setBackgroundImage(UIImage(named: "back.png"), for: .normal)
let barBackButtonItem = UIBarButtonItem(customView: backButton)
backButton.addTarget(target, action: action, for: .touchUpInside)
return barBackButtonItem
}


}


Now, I tried to use it by declaring a button in my viewcontroller where i need that by following way:

var backButton: UIButton! = nil


and in my
viewDidLoad
I'm declaring the following code:

self.navigationItem.leftBarButtonItem = backButton?.backButtonTarget(self, action: #selector(self.popCurrentViewController))


and in
popCurrentViewController


func popCurrentViewController() -> Void {

_ = self.navigationController?.popViewController(animated: true)

}


Here, by declaring above code, UINavigationBar leftbar item button should show as per my created button, but it is not showing neither it enter into the extension function either, but perfectly working on Objective c codes by using category, Where i'm doing wrong/ mistake here ? Any help will be appreciable.

Thanks

Answer

There is no button in navigationBar is because your backButton is nil, Currently you have added extension with instance method instead of that you need class method.

extension UIButton {

    class func backButtonTarget(_ target: Any, action: Selector) -> UIBarButtonItem {
        let backButton = UIButton(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(12), height: CGFloat(20)))
        backButton.setBackgroundImage(UIImage(named: "back.png"), for: .normal)
        let barBackButtonItem = UIBarButtonItem(customView: backButton)
        backButton.addTarget(target, action: action, for: .touchUpInside)
        return barBackButtonItem
    }
}

Now add BarButtonItem this way.

self.navigationItem.leftBarButtonItem = UIButton.backButtonTarget(self, action: #selector(self.popCurrentViewController))