以编程方式创建按钮并设置背景图像 [英] Create a button programmatically and set a background image

查看:15
本文介绍了以编程方式创建按钮并设置背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在 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)

这篇关于以编程方式创建按钮并设置背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆