Create a button programmatically and set a background image(以编程方式创建按钮并设置背景图像)
问题描述
当我尝试在 Swift 中创建按钮并设置背景图片时:
When I try creating a button and setting a background image in 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'".
I always get an error: "Cannot convert the expression's type 'Void' to type '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)
这篇关于以编程方式创建按钮并设置背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!