【问题标题】:Displaying Image On Button Swift在按钮 Swift 上显示图像
【发布时间】:2014-12-31 23:40:06
【问题描述】:

我尝试了此代码,但出现错误。我怎么能把图片放在按钮里。

Button.setBackgroundImage("ImageName", forState: UIControlState.Normal)

【问题讨论】:

  • 你遇到了什么错误?
  • Button是什么类?

标签: xcode button swift uiimage


【解决方案1】:

假设你所拥有的 Button 实际上是一个 UIButton 实例,仅仅传递图像的名称是不够的,你实际上需要传递一个实际的 UIImage:

let image = UIImage.named("ImageName")
myButton.setBackgroundImage(image!, forState: .Normal)

【讨论】:

    【解决方案2】:

    您必须创建一个使用您的图像初始化的UIImage 实例。然后将其用作按钮的图像

    【讨论】:

      【解决方案3】:

      不写代码也可以。只需将图像复制到您的项目中并执行以下步骤。然后,您可以使用约束更改按钮的大小和位置。

      【讨论】:

        【解决方案4】:

        问题的标题说您想要按钮上的图像,但您似乎在代码中使用了背景图像。无论哪种方式,两者都很容易实现。只需编写如下类似的代码

        let newButton = UIButton(type: .custom)
        
        newButton.setBackgroundImage(UIImage(named: "ImageName"), forState: .normal)
        

        现在,如果您想在按钮上设置图像,那么您可以使用:

        newButton.setImage(UIImage(named: "ImageName"), for: .normal)
        

        希望这会有所帮助。干杯!!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-07-23
          • 1970-01-01
          • 1970-01-01
          • 2018-01-11
          • 2013-06-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多