Create a button programmatically and set a background image

前端 未结 11 1095
自闭症患者
自闭症患者 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:06

    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)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-07 18:09

    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)
    
    0 讨论(0)
  • 2020-12-07 18:12

    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)
    
    0 讨论(0)
  • 2020-12-07 18:12

    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)
    
    0 讨论(0)
提交回复
热议问题