Objective-C:将字符串参数传递给手势@selector

sef*_*osu 4 objective-c selector gesture uigesturerecognizer ios

我要实现的目标是:当我点击特定的UIImageView时,UITapGesture会将字符串传递到tap方法中。

我的代码如下:假设我已经有一个UIImageView对象,当我点击此图像时,它将打个电话,

UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(makeCallToThisPerson:@"1234567")];
[imageViewOne addGestureRecognizer:tapFirstGuy];

- (void)makeCallToThisPerson:(NSString *)phoneNumber
{
    NSString *phoneNum = [NSString stringWithFormat:@"tel:%@", phoneNumber];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNum]];
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下编译错误: @selector(makeCallToThisPerson:@"1234567");

我不知道发生了什么事。为什么不能将字符串传递给private方法?

Oni*_* IV 5

这是错误的,它不是有效的选择器。

    UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(makeCallToThisPerson:@"1234567")];
Run Code Online (Sandbox Code Playgroud)

您需要更改为:

 UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(makeCallToThisPerson:)];
Run Code Online (Sandbox Code Playgroud)

在您的方法中,参数将是tapGesture,就是这样:

 - (void)makeCallToThisPerson:(UITapGestureRecognizer *)tapGesture
Run Code Online (Sandbox Code Playgroud)

您可以做几件事,以便输入一个参数:

1.-使用imageView的标签,tapGesture知道该视图比它所附的视图,您可以使用标签视图:

 UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(makeCallToThisPerson:)];
         imageViewOne.tag = 1234567
        [imageViewOne addGestureRecognizer:tapFirstGuy];

- (void)makeCallToThisPerson:(UITapGestureRecognizer *)tapGesture
 {
NSString *phoneNum = [NSString stringWithFormat:@"tel:%ld",tapGesture.view.tag];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNum]];
 }
Run Code Online (Sandbox Code Playgroud)

其他选项,子类化是为了将NSString附加到imageView作为新属性。


Hus*_*bir 5

您可以尝试编写如下子类的另一种方法UITapGestureRecognizer:-

@interface customTapGestureRecognizer : UITapGestureRecognizer

@property (nonatomic, strong) NSString * phoneNumber;

@end


// customTapGestureRecognizer.m

@implementation customTapGestureRecognizer

@end


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

....

customTapGestureRecognizer *singleTap = [[customTapGestureRecognizer alloc] initWithTarget:self action:@selector(makeCallToThisPerson:)];

singleTap.phoneNumber = @"1234567";


-(void) makeCallToThisPerson:(UITapGestureRecognizer *)tapRecognizer {

customTapGestureRecognizer *tap = (customTapGestureRecognizer *)tapRecognizer;

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

}
Run Code Online (Sandbox Code Playgroud)

注意: - 编写子类的优点是您可以在UITapGestureRecognizer.