Create a button programmatically and set a background image

前端 未结 11 1125
自闭症患者
自闭症患者 2020-12-07 17:44

When I try creating a button and setting a background image in Swift:

let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
    button.fram         


        
11条回答
  •  被撕碎了的回忆
    2020-12-07 18:07

    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)
    

提交回复
热议问题