How to add spacing to Left BarButtonItem Image with Swift 3

强颜欢笑 提交于 2019-12-24 09:57:44

问题


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

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.

Could anyone help me to solve this problem?


回答1:


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.")

}


来源:https://stackoverflow.com/questions/43337217/how-to-add-spacing-to-left-barbuttonitem-image-with-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!