小编典典

以编程方式创建按钮并设置背景图片

swift

当我尝试在Swift中创建按钮并设置背景图片时:

let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
    button.frame = CGRectMake(100, 100, 100, 100)
    button.setImage(IMAGE, forState: UIControlState.Normal)
    button.addTarget(self, action: "btnTouched:", forControlEvents: UIControlEvents.TouchUpInside)

    self.view.addSubview(button)

我总是收到一个错误:“ 无法将表达式的类型’Void’转换为’UIImage’ ”。


阅读 247

收藏
2020-07-07

共1个答案

小编典典

您的代码应如下所示

let image = UIImage(named: "name") as UIImage?
let button   = UIButton(type: UIButtonType.Custom) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "btnTouched:", forControlEvents:.TouchUpInside)
self.view.addSubview(button)
2020-07-07