Where you create your button add:
mybutton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
UIApplication.shared.keyWindow?.addSubview(mybutton)
Then in the same class add a method to handle whenever the button is pressed:
func buttonPressed() {
// Button handling code here e.g:
// StaticButtonHandler.handleButtonPress()
// or
// ButtonHandler.sharedInstance.handleButtonPress()
}
If you need global code to be called from anywhere and it doesn't require state it would be easiest to put it in some static method:
class StaticButtonHandler {
static func handleButtonPress() {
// Handle the button press
}
}
Alternatively use the singleton pattern:
class ButtonHandler {
static let sharedInstance = ButtonHandler()
func handleButtonPress() {
// Handle the button press
}
}