如何以编程方式将自定义图像设置为和UIBarButtonItem

时间:2019-04-04 22:09:42

标签: ios swift xcode uiimage uibarbuttonitem

我在将自定义图像分配给UIBarButtonItem时遇到问题,主要问题是创建按钮时图像显示为白色正方形。 这是我的代码:

fileprivate func configureNavigationBar() {
        tabBarController?.navigationItem.title = lot.name
        let exportImg: UIImage = UIImage(named: "action.png")!
        let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showCreationView(_:)))
        let exportByEmail = UIBarButtonItem(image: exportImg, style: .done, target: self, action: #selector(exportDataByEmail(_:)))
        tabBarController?.navigationItem.rightBarButtonItems = [exportByEmail,addButton]
    }

问题出在 exportByEmail ,图像在我的资产中添加的变量 exportImg 中:

image1

从我的代码获得的结果: image2

1 个答案:

答案 0 :(得分:1)

您的图片背景必须是透明的,并且您可以将始终原始的渲染模式设置为图片,以便按如下所示进行显示而无需更改

let exportByEmail = UIBarButtonItem(image: exportImg.withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(exportDataByEmail(_:)))