What I am trying to achieve is this: when I tap an specific UIImageView, the UITapGesture will pass a string into the tap method.
My code follows below: Imagine I have an UIImageView object there already, and when I tap this image, it will make a phone call,
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]];
}
However, I am getting the following compile error: @selector(makeCallToThisPerson:@"1234567");
I cannot figure what is happening. Why can't I pass string to the private method?
One more way you can try writing subclass of UITapGestureRecognizer
like that below:-
@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);
}
Note:- The advantages of writing subclass is that you can pass more number of data easily in your UITapGestureRecognizer
.
This is wrong, It's not a valid selector.
UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(makeCallToThisPerson:@"1234567")];
You need to change to this:
UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(makeCallToThisPerson:)];
In your methods the parameter will be the tapGesture, that's it:
- (void)makeCallToThisPerson:(UITapGestureRecognizer *)tapGesture
You can do several things, in order to pas a parameter:
1.- Use de tag of the imageView, the tapGesture knows the view than it´s attached you can use the tag view:
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]];
}
Other option, subclassing in order to attach a NSString to imageView as a new property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With