Determine if responder chain will handle an action
Asked Answered
W

2

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.

Wandis answered 9/1, 2015 at 15:31 Comment(0)
W
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;
Wandis answered 9/1, 2015 at 16:7 Comment(0)
A
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

Allveta answered 9/1, 2015 at 16:0 Comment(3)
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.Wandis
Sounds like I'm about to learn something new by reading the article you linked to then :)Allveta
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.Wandis

© 2022 - 2024 — McMap. All rights reserved.