Benjohn Benjohn -4 years ago 89
iOS Question

Determine if responder chain will handle an action

The responder chain is cool.

Particularly, being able to send custom actions to the first responder that will bubble up to anyone else that might be interested:

[[UIApplication sharedApplication] sendAction: @selector(commandToSend) to: nil from: self forEvent: nil]

Or less custom actions with:

[[UIApplication sharedApplication] sendAction: @selector(resignFirstResponder) to: nil from: self forEvent: nil]

I'd like to know – is there a way to test before hand if a particular action from a particular sender would be handled if it were sent now? An obvious use for this would be to enable and disable buttons that send actions dependent on whether that action is going to be handled at the moment.

If you happen to know the first responder, I think you can do
[aResponder targetForAction: @selector(methodYouWantToSend) withSender: selfOrSomethingElse]
, and check whether the answer is nil or not. But there doesn't seem to be a an equivalent method to
that will automatically start at the first responder and work up.

Answer Source

There's a delightful solution here to finding the first responder by exploiting the responder chain.

Once you know the first responder, it's easy to ask if the current responder chain handles a particular action. You can even find out who'll be handling it, should you wish.

const SEL action = @selector(theActionYouWantToSend);
UIResponder *const currentTarget = [[UIResponder firstResponder] targetForAction: action  withSender: self];
const bool actionIsHandled = currentTarget != nil;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download