Make a UIButton programmatically in Swift

后端 未结 19 1860
死守一世寂寞
死守一世寂寞 2020-11-27 10:00

I am trying to build UI\'s programmatically. How do I get this action working? I am developing with Swift.

Code in viewDidLoad:

over         


        
19条回答
  •  没有蜡笔的小新
    2020-11-27 10:27

    Swift 3: You can create a UIButton programmatically

    either inside a methods scope for example in ViewDidLoad() Be sure to add constraints to the button, otherwise you wont see it

    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.target(forAction: #selector(buttonAction), withSender: self)
    //button.backgroundColor etc
    
    view.addSubview(button)
    
    @objc func buttonAction() {
       //some Action
    }
    

    or outside your scope as global variable to access it from anywhere in your module

    let button: UIButton = {
       let b = UIButton()
       b.translatesAutoresizingMaskIntoConstraints = false
       //b.backgroundColor etc
       return b
    }()
    

    and then you setup the constraints

    func setupButtonView() {
       view.addSubview(button)
       button.widthAnchor.constraint(equalToConstant: 40).isActive = true
       button.heightAnchor.constraint(equalToConstant: 40).isActive = true
       // etc
    
    }
    

提交回复
热议问题