如何使用 Swift 3 向左 BarButtonItem 图像添加间距 [英] How to add spacing to Left BarButtonItem Image with Swift 3

查看:61
本文介绍了如何使用 Swift 3 向左 BarButtonItem 图像添加间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在栏按钮的左侧添加空间.

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?

推荐答案

Hi 下面给出的代码可能对您有用.

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
    }
}

您可以根据您对左填充的要求为 UIEdgeInsetsMake(0, -50, 0, 0) 增加或减少 Left Padding.

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

}

这篇关于如何使用 Swift 3 向左 BarButtonItem 图像添加间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆