7

How do I add a IBAction to a button programmatically?

button.addTarget(self, action: Selector(("buttonAction:")), for: 
.touchUpInside)

func buttonAction(sender: Any) {
    print("test")
}

That gives me an "Thread 1: signal SIGABRT" error.

3
  • "You deleted an Outlet/Action connection in code or renamed it (spelling mistake?)." - is not the case :') Commented Oct 26, 2017 at 9:02
  • btn.addTarget(self, action: #selector(testFunction(_:)), for: .touchDown) swift 3.2 Commented Oct 26, 2017 at 9:04
  • Technically, you don't "add" an IBAction programmatically - the "IB" stands for "Interface Builder". What you mean to ask is how use the sender in an addTarget(action:) call. Commented Oct 26, 2017 at 9:44

1 Answer 1

15

Swift 4 version:

button.addTarget(self, action: #selector(action(sender:)), for: .touchUpInside)

@objc private func action(sender: Button) {
    print("test")
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your reply, yea I've seen this code before. But Swift yells at me with: "Argument of '#selector' refers to instance method 'buttonAction(sender:)' that is not exposed to Objective-C Add '@objc' to expose this instance method to Objective-C"
that's why there is the @objc annotation
@Mofawaw then add "@objc", should look like "@objc func buttonAction()"
@objc func action(sender: Button)
I had to wait 2 minutes, not my programming. :')
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.