When I try creating a button and setting a background image in Swift:
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.fram
Create Button and add image as its background swift 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)
You need check for image is not nil before assign it to button.
Example:
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)
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)
Update to 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)
Swift: Ui Button create programmatically
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)