Determine if responder chain will handle an action

倖福魔咒の 提交于 2019-12-23 13:22:39

问题


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.


回答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;



回答2:


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



来源:https://stackoverflow.com/questions/27863940/determine-if-responder-chain-will-handle-an-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!