小编典典

将自定义图像设置为UIBarButtonItem,但不显示任何图像

swift

我想将自定义图像设置为UIBarButtonItem,但它仅在周围显示一个矩形框,并且不显示实际图像。

func setupBrowserToolbar() {
    let browser = UIToolbar(frame: CGRect(x: 0, y: 20, width: self.view.frame.width, height: 30))
    //配置返回组件
    let path = NSBundle.mainBundle().pathForResource("back", ofType: "png")
    let urlstr = NSURL(fileURLWithPath: path!)
    let data = NSData(contentsOfURL: urlstr)
    let btnback = UIBarButtonItem(image: UIImage(data: data!), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("backClicked:"))
    //分割按钮1
    let btngrap1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    //前进按钮
    let btnforward = UIBarButtonItem(image: UIImage(named: "forward.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("forwardClicked:"))
    //分割按钮2
    let btngrap2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    //重新加载
    let btnreload = UIBarButtonItem(image: UIImage(named: "reload.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("reloadClicked:"))
    //分割按钮3
    let btngrap3 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    //停止加载
    let btnstop = UIBarButtonItem(image: UIImage(named:"stop.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("stopClicked:"))
    progress = UIProgressView((frame: CGRect(x: 0, y: 48, width: self.view.frame.width-50, height: 2)))
    progress.progress = 0
    browser.setItems([btnback, btngrap1, btnforward, btngrap2, btnreload, btngrap3, btnstop], animated: true)
    ptimer = NSTimer(timeInterval: 0.2, target: self, selector: Selector("loadProgress"), userInfo: nil, repeats: true)
    self.view.addSubview(browser)
}

我的应用程序屏幕截图

上面的方法是工具栏配置,但是我不知道这是什么错误。


阅读 407

收藏
2020-07-07

共1个答案

小编典典

那是因为UIBarButtonItem图像的默认呈现模式始终将图像绘制为模板图像,而忽略其颜色信息(UIImageRenderingModeAlwaysTemplate)。只需使用UIImage的方法imageWithRenderingMode始终创建原始图像即可。

UIImage(named: "yourImageName")!.withRenderingMode(.alwaysOriginal)
2020-07-07