如何将背景图像添加到UIBarButtonItem

时间:2016-08-25 22:22:04

标签: ios swift uiimage uibarbuttonitem

我有以下代码,当点击textField时,会在键盘顶部添加一个UIToolbar。

如何将背景图像添加到其中一个按钮?

我试过......

toolBar.items![1].setBackButtonBackgroundImage(clearButton, forState:.Normal, barMetrics:.Default) 

但它没有用,我收到错误......

  

使用未解析的标识符' imageName'

代码:

func addButtonsToKeyboard(){
    let toolBar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
    toolBar.barStyle = UIBarStyle.Default
    toolBar.tintColor = UIColor.blueColor()
    toolBar.barTintColor = UIColor.grayColor()
    toolBar.items = [
        UIBarButtonItem(title: "Button1", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(someFunction)),
        UIBarButtonItem(title: "Button2", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(someFunction)),
        UIBarButtonItem(title: "Button3", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(someFunction))]

    toolBar.sizeToFit()

    toolBar.items![1].setBackButtonBackgroundImage(myImage, forState:.Normal, barMetrics:.Default)

    myTextField.inputAccessoryView = toolBar
}

BTW - 图片myImage位于Assets.xcassets

1 个答案:

答案 0 :(得分:1)

也许您可以尝试创建一个UIImage变量,然后将其传递给更明确:

var myImage = UIImage(named: "myImage")
toolBar.items![1].setBackButtonBackgroundImage(myImage, forState:.Normal, barMetrics:.Default)