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


75

当我尝试在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' ”。


您可以在声明的位置显示代码IMAGE吗?
67樱桃2014年

2
您如何创建图像?可能需要解开它的图像!
Alex Reynolds

1
IMAGE应该看起来像UIImage(named: "name")
Daniel

谢谢你的作品!我只说过:“ button.setImage(“ CircleTap”,forState:UIControlState.Normal)”,但是现在它可以正常工作了
加里(Gary

Answers:


139

您的代码应如下所示

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)

2
我认为实际上应该是as? UIImage 如果imageNamed:返回nil,您的版本将崩溃。
David Berry 2014年

3
好吧,这是您的错(如果没有),但是您可以添加?但是那时候你也必须意识到setImage。我想这取决于您希望获得的防御力,并且由于您控制本地资产,因此一两个单元测试就不会让人感到惊讶
Alex Reynolds 2014年

1
圆圈图像呢?
2014年

尝试添加?as UIImage?
Alex Reynolds

4
如果不想看到蓝色按钮button = UIButton.buttonWithType(UIButtonType.Custom)作为UIButton,请将按钮类型更改为“自定义”
iluvatar_GR 2014年

26

请尝试以下方法:

let image = UIImage(named: "ImageName.png") as UIImage
var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button .setBackgroundImage(image, forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents:UIControlEvents.TouchUpInside)
menuView.addSubview(button)

让我知道它是否有效?


您应该将buttonWithType设置为UIButtonType.Custom,而不是System,直到图像显示为止
sazz

9

SWIFT 3版本的Alex Reynolds的答案

let image = UIImage(named: "name") as UIImage?
let button = UIButton(type: UIButtonType.custom) as UIButton
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: Selector("btnTouched:"), for:.touchUpInside)
        self.view.addSubview(button)

8

Swift 5版本接受的答案:

let image = UIImage(named: "image_name")
let button = UIButton(type: UIButton.ButtonType.custom)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: #selector(function), for: .touchUpInside)

//button.backgroundColor = .lightGray
self.view.addSubview(button)

当然在哪里

@objc func function() {...}

图像默认对齐中心。您可以通过设置按钮的imageEdgeInsets来更改此设置,如下所示:

// In this case image is 40 wide and aligned to the left
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: button.frame.width - 45)

6

您需要先检查图像是否为nil,然后再将其分配给按钮。

例:

let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
if let image  = UIImage(named: "imagename.png") {
    button.setImage(image, forState: .Normal)
}

button.addTarget(self, action: "btnTouched:", forControlEvents:.TouchUpInside)
self.view.addSubview(button)

我想如果图像不在项目中,我希望该应用程序崩溃。那为什么要检查?
杰夫

因为该应用程序不会崩溃,并且可能会附带丢失的图像
MacInnis

6

创建按钮并将图像添加为其背景雨燕4

     let img = UIImage(named: "imgname")
     let myButton = UIButton(type: UIButtonType.custom)
     myButton.frame = CGRect.init(x: 10, y: 10, width: 100, height: 45)
     myButton.setImage(img, for: .normal)
     myButton.addTarget(self, action: #selector(self.buttonClicked(_:)), for: UIControlEvents.touchUpInside)
     self.view.addSubview(myButton)

更正:第4行] button.setImage(image,for:.normal)
MacInnis

4
let btnRight=UIButton.buttonWithType(UIButtonType.Custom) as UIButton
btnRight.frame=CGRectMake(0, 0, 35, 35)
btnRight.setBackgroundImage(UIImage(named: "menu.png"), forState: UIControlState.Normal)
btnRight.setTitle("Right", forState: UIControlState.Normal)
btnRight.tintColor=UIColor.blackColor()

4

这样可以创建带有边框和圆角边缘的漂亮按钮:

loginButton = UIButton(frame: CGRectMake(self.view.bounds.origin.x + (self.view.bounds.width * 0.325), self.view.bounds.origin.y + (self.view.bounds.height * 0.8), self.view.bounds.origin.x + (self.view.bounds.width * 0.35), self.view.bounds.origin.y + (self.view.bounds.height * 0.05)))
loginButton.layer.cornerRadius = 18.0
loginButton.layer.borderWidth = 2.0
loginButton.backgroundColor = UIColor.whiteColor()
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.setTitleColor(UIColor(red: 24.0/100, green: 116.0/255, blue: 205.0/205, alpha: 1.0), forState: UIControlState.Normal)

3

要设置背景,我们不能再使用forState,因此我们必须使用for来设置UIControlState

let zoomInImage = UIImage(named: "Icon - plus") as UIImage?
let zoomInButton = UIButton(frame: CGRect(x: 10), y: 10, width: 45, height: 45))
zoomInButton.setBackgroundImage(zoomInImage, for: UIControlState.normal)
zoomInButton.addTarget(self, action: #selector(self.mapZoomInAction), for: .touchUpInside)
self.view.addSubview(zoomInButton)

我使用此代码在Google地图上放置缩放按钮。使用上面的代码设置背景图像。与以前不同。
Shazoo

但是,它与其他答案有何不同?
Leopold Joy

现在要设置背景,我们现在不能使用forState,我们必须使用“ for”来设置UIControlState
Shazoo

2

更新到Swift 3

let image = UIImage(named: "name")
let button = UIButton(type: .custom)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: #selector(self.btnAbsRetClicked(_:)), for:.touchUpInside)
self.view.addSubview(button)

1

Swift:Ui Button以编程方式创建

let myButton = UIButton()

myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)

myButton.titleLabel!.text = "Button Label"

myButton.titleLabel!.textColor = UIColor.redColor()

myButton.titleLabel!.textAlignment = .Center

myButton.addTarget(self,action:"Action:",forControlEvents:UIControlEvent.TouchUpInside)

self.view.addSubview(myButton)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.