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

How to set a Custom image programmatically to and 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 中:

从我的代码中得到的结果:

你的图片背景必须是透明的,你可以设置always original rendering mode为image,原样显示如下

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