May Phyu
May Phyu

Reputation: 905

How to add spacing to Left BarButtonItem Image with Swift 3

I would like to add space to the left of the bar button.

enter image description here

So, I add this code.

    navbar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin, .flexibleRightMargin]
    navbar.delegate = self

    UINavigationBar.appearance().barTintColor = UIColor(red: 0.0/255.0, green:49.0/255.0, blue:79.0/255.0, alpha:0.1)

    UINavigationBar.appearance().tintColor = UIColor.white
    UINavigationBar.appearance().isTranslucent = true
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]

    navItem.title = prefs.value(forKey: "PROVIDER_NAME") as! String?
    let image = UIImage(named: "back_image")
    navItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(addTapped))

After adding this code, the button image does not show well and looks no good.

enter image description here

Could anyone help me to solve this problem?

Upvotes: 1

Views: 3098

Answers (1)

mrunal thanki
mrunal thanki

Reputation: 751

Hi Code given below might be useful for you.

extension UIBarButtonItem {
    class func itemWith(colorfulImage: UIImage?, target: AnyObject, action: Selector) -> UIBarButtonItem {
        let button = UIButton(type: .custom)
        button.setImage(colorfulImage, for: .normal)
        button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
        button.imageEdgeInsets = UIEdgeInsetsMake(0, -50, 0, 0)
        button.addTarget(target, action: action, for: .touchUpInside)

        let barButtonItem = UIBarButtonItem(customView: button)
        return barButtonItem
    }
}

You can increase or decrease Left Padding for UIEdgeInsetsMake(0, -50, 0, 0) as per your requirement for left padding.

You can use above extension in your code as describe below.

self.navigationItem.leftBarButtonItem = UIBarButtonItem.itemWith(colorfulImage: UIImage(named: "ic_back")?.withColor(UIColor.white), target: self, action: #selector(btnBackClicked))

func btnBackClicked() {
    print("your code here on back button tapped.")

}

Upvotes: 3

Related Questions