Pass a NSDictionary as parameter to UITapGestureRecognizer

对着背影说爱祢 提交于 2019-11-27 07:13:35

问题


I want to pass a NSArray as a parameter to UITapGestureRecognizer and access it in downloadOptionPressed method. How can I do this ?

The NSArray

NSArray *parameters = [NSArray arrayWithObjects:currentTrack, nil];

Creating the UITapGestureRecognizer

UITapGestureRecognizer *downloadOptionPressed = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(timeFrameLabelTapped:)];
    [downloadOption addGestureRecognizer:downloadOptionPressed];

The downloadOptionPressed method

-(void)downloadOptionPressed:(UIGestureRecognizer*)recognizer{

}

回答1:


Is there a reason you can't store the information in the owning view controller? Is it for abstraction?

You can always extend UITapGestureRecognizer to carry more data:

@interface UserDataTapGestureRecognizer : UITapGestureRecognizer
@property (nonatomic, strong) id userData;
@end

@implementation UserDataTapGestureRecognizer
@end

...

UserDataTapGestureRecognizer *downloadOptionPressed =
    [[UserDataTapGestureRecognizer alloc] initWithTarget:self
    action:@selector(timeFrameLabelTapped:)];
downloadOptionPressed.userData = parameters;

...

- (void)downloadOptionPressed:(UserDataTapGestureRecognizer *)recognizer {
    NSArray *parameters = recognizer.userData;
}



回答2:


You can use associated object to pass argument along with tap gesture instance.

You can check this objective-c-associated-objects

It will solve your problem.




回答3:


Sometimes with passing an index is enough, in that case the tag property view is your ally. In the following exampled I pretended to add a long press into a tableview cell. And once the event was triggered, I just wanted to know which cell was long pressed:

    let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
    cell.tag = indexPath.row
    cell.addGestureRecognizer(longPress)

...

func longPress(guesture: UILongPressGestureRecognizer) {
    print("\(guesture.view!.tag)")} }


来源:https://stackoverflow.com/questions/16110422/pass-a-nsdictionary-as-parameter-to-uitapgesturerecognizer

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