Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Introduction to Auto Layout in iOS Auto Layout in Code Setting Up the Orange View

IBActions on CodeLayout

how do i make IBActions on a button i made in code

3 Answers

thanks bro

but how do i do than on an instance of UIButton

Arman Arutyunov
Arman Arutyunov
21,900 Points

What do you mean? My example is actually dealing with a UIButton instance.

See the first line. I instantiate UIButton to the "button" constant:

let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

And then I "addTarget" to that constant with a selector on a method I want to be called when the button is tapped:

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

And that is a method I specified in the addTarget method which will be called every time the button is tapped (just like an IBAction)

func buttonAction(sender: UIButton!) {
  print("Button tapped")
}
Arman Arutyunov
Arman Arutyunov
21,900 Points

If it helped you could mark my answer as correct so other students can see it and not ask the same question in the future

Arman Arutyunov
Arman Arutyunov
21,900 Points

You don't make IBActions on button you create programmatically. The way you do it is by addTarget method.

That's an example

override func viewDidLoad() {
  super.viewDidLoad()

  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
  button.backgroundColor = .green
  button.setTitle("Test Button", for: .normal)
  button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

  self.view.addSubview(button)
}

func buttonAction(sender: UIButton!) {
  print("Button tapped")
}

buttonAction() is your IBAction analogue. You can name it anyway you want, of course.

Hope it helps!

no