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 trialShaurya Grover
15,815 PointsIBActions on CodeLayout
how do i make IBActions on a button i made in code
3 Answers
Shaurya Grover
15,815 Pointsthanks bro
Arman Arutyunov
21,900 PointsYou 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!
Shaurya Grover
15,815 Pointsno
Shaurya Grover
15,815 PointsShaurya Grover
15,815 Pointsbut how do i do than on an instance of UIButton
Arman Arutyunov
21,900 PointsArman Arutyunov
21,900 PointsWhat 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)
Arman Arutyunov
21,900 PointsArman Arutyunov
21,900 PointsIf it helped you could mark my answer as correct so other students can see it and not ask the same question in the future