How to call a function from a Button in Swift
14:45 23 Feb 2026

I am VERY new to Swift! Pleas have mercy on my basic question.

I'm trying programmatically set up a button. I call a function like so:

override func viewDidLoad() {
        super.viewDidLoad()

        var yCord1 = 100
        var yCord2 = 200

        setUpButton("YES", yCord1)
        setUpButton("NO", yCord2)
}

The function:

func setupButton(_ text:String, _ yCord:Int) {
          
        let myButton = UIButton()
        
        myButton.setTitle(text, for: .normal)
        myButton.setTitleColor(.white, for: .normal)
        
        myButton.backgroundColor = .blue
        myButton.frame = CGRect(x: 100, y: yCord, width: 100, height: 50)
        
     
       // this didn't work:
       // myButton.addAction(selector(tapButton()), for: .touchUpInside)
        
       // this also didn't work..\
        myButton.addTarget(self, action: #selector(buttonTap), for: .touchUpInside)


        // ADD TO VIEW
        self.view.addSubview(myButton)
    }

The function I want the button to call:

func tapButton(_ text:String) {
        
      if text == "YES" {
           print("Yes button has been tapped!")
      } else {
           print("NO button tapped")
}

I cannot figure out the code to pass in to address assigning a function to the button. It looks like there are 2 options:

myButton.addAction(...

or

myButton.addTarget(...

I couldn't get either to work, I get stuck at what code do I add to the action portion - the for: touchUpInside appears to work OK. I also haven't found an example where I can pass a value through. If that's not possible I think I can develop a work around. Thanks in advance.

swift xcode swiftui