質問

Basically I want to get a list of action targets for a UIButton. I have gone through this and my question is slightly different because I do not know what the target is. All I have is a UIButton object. So here's what I did to capture all action targets.

Inspired by below method which works where I get firstResponder object as valid pointer.

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView   *firstResponder = [keyWindow performSelector:@selector(firstResponder)];

I used class-dump on UIKit to see UIWindow class and I found firstResponder as below.

 NS_CLASS_AVAILABLE_IOS(2_0) @interface UIWindow : UIView {
  @package
    UIResponder             *_firstResponder;
}

Then I checked UIControl which via class-dump as

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIControl : UIView {
  @package
     NSMutableArray* _targetActions;
 }

So here's what I try to do and it crashes.

    NSMutableArray *arr = (NSMutableArray*)[((UIControl*)btn) performSelector:@selector(targetActions)];
    NSLog(@"%@",arr);

Sounds like conspiracy against me. But more likely I am goofing up some thing. Does any know how to access targetActions Array of UIControl?

EDIT: Here's the error message -

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-    [UIRoundedRectButton targetActions]: unrecognized selector sent to instance 0x1c0ab0'

Any help appreciated.

役に立ちましたか?

解決

According to the UIControl documentation, the message to send to get a list of targets is allTargets not targetActions as you suggest. The rest of the solution is in the accepted answer to How to get UIButton Target, Action and Control events?

A debugging technique you can use when you don't know what you're doing is to use respondsToSelector to check whether you're sending a message that the object can respond to: when to use respondsToSelector in objective-c

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top