How do I create a basic UIButton programmatically?

后端 未结 30 1387
清歌不尽
清歌不尽 2020-11-22 14:41

How can I create a basic UIButton programmatically? For example in my view controller, when executing the viewDidLoad method, three UIButton<

30条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 15:22

    As of Swift 3, several changes have been made to the syntax.

    Here is how you would go about creating a basic button as of Swift 3:

        let button = UIButton(type: UIButtonType.system) as UIButton
        button.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
        button.backgroundColor = UIColor.green
        button.setTitle("Example Button", for: UIControlState.normal)
        self.view.addSubview(button)
    

    Here are the changes that have been made since previous versions of Swift:

    let button = UIButton(type: UIButtonType.System) as UIButton
    
    // system no longer capitalised
    
    button.frame = CGRectMake(100, 100, 100, 50)
    
    // CGRectMake has been removed as of Swift 3
    
    button.backgroundColor = UIColor.greenColor()
    
    // greenColor replaced with green
    
    button.setTitle("Example Button", forState: UIControlState.Normal)
    
    // normal is no longer capitalised
    
    self.view.addSubview(button)
    

提交回复
热议问题