Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a button programmatically and set a background image

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) 

I always get an error: "Cannot convert the expression's type 'Void' to type 'UIImage'".

like image 271
Gary Avatar asked Jun 05 '14 15:06

Gary


1 Answers

Your code should look like below

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) 
like image 124
Alex Reynolds Avatar answered Sep 18 '22 17:09

Alex Reynolds