将参数传递给 UITapGestureRecognizer [重复]

Posted

技术标签:

【中文标题】将参数传递给 UITapGestureRecognizer [重复]【英文标题】:pass parameter to UITapGestureRecognizer [duplicate] 【发布时间】:2013-10-31 10:18:51 【问题描述】:

我已经创建了动态的UIimage 视图和UITapGestureRecognizer 以使其看起来像这样

UIImageView *image = [[UIImageView alloc ] initWithFrame:CGRectMake(x, 0, 200, 150)];
        NSString *ImageURL = [str objectForKey:@"imageLink"];
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
        image.image = [UIImage imageWithData:imageData];

        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];

        singleTap.numberOfTapsRequired = 1;
        image.userInteractionEnabled = YES;

        [image addGestureRecognizer:singleTap];

        [documentory addSubview:image]; 

和我这样的操作方法

-(void)tapDetected:(UIGestureRecognizer *)recognizer
    NSLog(@"single Tap on imageview");


我想将一个字符串参数传递给tapDetected方法,谁能告诉我该怎么做,非常感谢

【问题讨论】:

你需要传递什么? 我不确定我们是否可以将参数添加到gestureRecognizer 属性。您想从哪个元素获取字符串? 取一个全局变量并根据需要更改该变量的值。 我想传递 imageUrl 和一些字符串参数 【参考方案1】:

您可以扩展一个 UITapGestureRecognizer 来保存更多数据:

// MYTapGestureRecognizer.h

@interface MYTapGestureRecognizer : UITapGestureRecognizer

@property (nonatomic, strong) NSString *data;

@end


// MYTapGestureRecognizer.m

@implementation MYTapGestureRecognizer

@end


// =====================

....

MYTapGestureRecognizer *singleTap = [[MYTapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];

singleTap.data = @"Hello";

.....


// ====================

-(void)tapDetected:(UITapGestureRecognizer *)tapRecognizer 

MYTapGestureRecognizer *tap = (MYTapGestureRecognizer *)tapRecognizer;

NSLog(@"data : %@", tap.data);


【讨论】:

太棒了。正是我想要的。【参考方案2】:

传递发送者,

- (void)tapDetected:(UIGestureRecognizer *)sender

    NSLog(@"%@", sender.view);   // imageview 

【讨论】:

以上是关于将参数传递给 UITapGestureRecognizer [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何将参数传递给进程

如何通过反射将参数传递给方法

如何将参数传递给 erlang os:cmd()?

将 NSDictionary 作为参数传递给 UITapGestureRecognizer

如何将两个参数传递给 Pool.starmap()?

将参数传递给windows计划任务