当我尝试在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’ ”。
您的代码应如下所示
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)