-1

I have added a button, which I want to see top of all my ViewControllers with

UIApplication.shared.keyWindow?.addSubview(mybutton)

What I am trying to figure out is how can I make a global function that this button can call, no matter of which is my current ViewController ?

Jack
  • 13,571
  • 6
  • 76
  • 98
radioaktiv
  • 2,437
  • 4
  • 27
  • 36

2 Answers2

0

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
    }
}
  • Thanks, but that not I need. Please read the question. I am ofc aware that I can do that but it will work for the current ViewController that I am in. Again what I want is a global function that can be called from anywhere. – radioaktiv Oct 17 '17 at 13:36
  • Added static method and singleton pattern to my answer to allow global code to be called from your button handler, or anywhere else, does that help? – Mike Atkins-Spelling Oct 18 '17 at 07:37
0

You could declare a class in your code that will hold the "global" action method:

class GlobalActionHandler {
    @objc static func buttonClicked() {
        print("Button click handler")
    }
}

Then add a target and action to your button like this:

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

You could also make GlobalActionHandler a singleton and buttonClicked() an instance method if you prefer.

Lubo
  • 192
  • 3
  • 10