UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.