4

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 UIApplication's sendAction:… that will automatically start at the first responder and work up.

Benjohn
  • 12,147
  • 8
  • 58
  • 110

2 Answers2

1

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;
Community
  • 1
  • 1
Benjohn
  • 12,147
  • 8
  • 58
  • 110
0

You can check if the responder can respond to the action like this:

[aResponder respondsToSelector:@selector(methodToSend)];

If it can respond, it'll return YES. Then you know it's safe to call that method

Chris
  • 6,863
  • 17
  • 64
  • 108
  • This doesn't work for the responder chain. It only asks `aResponder` if _it_ can handle a method. It doesn't ask **the responder chain** if it can handle a method. – Benjohn Jan 09 '15 at 16:01
  • Sounds like I'm about to learn something new by reading the article you linked to then :) – Chris Jan 09 '15 at 16:03
  • You totally are, dude. It's awesome. It also boggles me it's not more widely known – it's extremely powerful and elegant. For example, it provides a great deal of what you would need if you wanted to implement unwind segues. – Benjohn Jan 09 '15 at 16:11