Swift code to make a button.

Home Forums iA Coders Swift code to make a button.

Viewing 1 reply thread
  • Author
    • #2739
      Michael Doise

      Hello everyone,

      I have received requests on how to make a button with an action programmatically. Here is the code to use for Swift 4. You should be using Swift 4 code, so here we go.

      let button = UIButton()
       button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
       button.backgroundColor = UIColor.red
       button.setTitle("Name your Button ", for: .normal)
       button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
       @objc func buttonAction(sender: UIButton!) {
          print("Button tapped")
    • #2740
      Michael Doise

      Let me know if this doesn’t work. The target selector may be written incorrectly based on my own code.

Viewing 1 reply thread
  • You must be logged in to reply to this topic.