TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Add an action to a button in a custom vIew

Forums > iOS

I have a custom view (programmatically) with a button. I add it as subview to the view of my viewcontroller. How do I add a target to the button in my custom view in this viewcontroller (how do I reference it) ?

For now I've added a tag of 100 to my button in my custom view class. IN the viewcontroller I reference it as follows:

guard let okButton = helpView.viewWithTag(1000) as? ProjectButton else { return }
okButton.addTarget(self, action: #selector(dismissHelp), for: .touchUpInside)

3      

I think the best way is to have closure property on your custom view, create @IBAction for this button in your custom view and in the action code run this closure :-)

You can then assign any kind of method or closure to the property of the view to get fired by tap on the button.

3      

Thing is I am not using storyboards, so all programatically. So I can't use @IBAction. Is there another way than the way I did it above?

3      

You are right, in that case just mark the method as @objc and in your view constructor call the addTarget everything else should stay the same

3      

Is that subview creation code is in the same file where viewcontroller?

In that case you could create in the top of viewcontroller class that button property var okButton: ProjectButton? without initialization, and initialize it when you are creating your subview. So then you can reference your okButton from anywhere in your code in that file.

3      

@Sangsom; different file.

I'm gonna keep it like it is, with the tag. Works, so ....

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.