一尘不染

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

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’ ”。


阅读 216

收藏
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