iosswiftuicontroltarget-action

How do I find the action function for a target in iOS


I hope I can make this clear. I have button and I want to know what function in what object is the target for it's .touchDown event. There are properties and functions in iOS that might be what I'm looking for, but I can't make them work. The property is: self.allTargets the function is: self.actions(forTarget:, forControlEvent:)

I've printed the values with this code:

print( self.allTargets )
print( self.actions(forTarget: self, forControlEvent: .touchDown) ?? "no targets")
print( self.actions(forTarget: Button_Test.ViewController , forControlEvent: .touchDown) ?? "no targets")
print( self.actions(forTarget: "ViewController", forControlEvent: .touchDown) ?? "no targets")

result:

[AnyHashable(<Button_Test.ViewController: 0x7b293300>)]
no targets
no targets
no targets

I can see the button has a target, but I can't get the function. Help!


Solution

  • To get all target/action pairs for a given control event (.touchDown in this case), you need to do the following:

    let targets = self.allTargets
    for target in targets {
        if let actions = self.actions(forTarget: target, forControlEvent: .touchDown) {
            for action in actions {
                print("taget: \(target) - \(action)")
            }
        }
    }
    

    Basically you need to iterate through all of the targets and get the list of actions for each target for the given event.