开发者

Custom actions for UIGestureRecognizers (with custom parameters)

开发者 https://www.devze.com 2023-02-10 23:38 出处:网络
Short version of my problem: I cannot figure out how to make the \"action\" for my UITapGestureRecognizer take additional parameters, and actually use them.

Short version of my problem:

I cannot figure out how to make the "action" for my UITapGestureRecognizer take additional parameters, and actually use them.

Here's the rundown of my problem:

I am trying to make it so that my iPad app records (with NSLog) the coordinates of the UITouch that occurs whenever they press one of my app's UIButtons. The location of the touch needs to be 开发者_StackOverflowrelative to the button that was touched.

What I've done:

I have implemented a UITapGestureRecognizer and added it to each of my buttons. My problem is with the action to use, since it needs to be dynamic for each and every button.

I currently have this code:

 UITapGestureRecognizer *iconClickRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(logIcon:withTag:)];
 [iconClickRecognizer setNumberOfTapsRequired:1];
 [iconClickRecognizer setNumberOfTouchesRequired:1];
 [iconClickRecognizer setDelegate:self];
 [[self.view viewWithTag:1] addGestureRecognizer:iconClickRecognizer];

 [iconClickRecognizer release];

When I know that this works, I will use a for-loop to add the iconClickRecognizer to all of the buttons by their tag.

The logIcon:(int)withTag method is shown here:

-(void)logIcon:(UIGestureRecognizer *)gestureRecognizer withTag:(int)tag {
  NSLog(@"tag X: %f", [gestureRecognizer locationInView:(UIView*)[self.view viewWithTag:tag]].x);
  NSLog(@"tag Y: %f", [gestureRecognizer locationInView:(UIView*)[self.view viewWithTag:tag]].y);
}

What isn't working:

When I hard-code a tag into logIcon method, it records the information correctly. However, I do not know how to make this method dynamic, and actually use the "tag" parameter.

Any help would be greatly appreciated.

Thanks, Alex


The issue is that you can only get one argument from target / action style registration, that is the sender (in this case the gesture recognizer itself). You're not able to pass arbitrary contexts. But you could, in your action, check the recognizer's view property and examine that view's tag.


The docs for UIGestureRecognizer class specify that the action must be of the form:

- (void)handleGesture;
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;

not your form of:

- (void)logIcon:(UIGestureRecognizer *)gestureRecognizer withTag:(int)tag

So you could ask the gestureRecognizer where it is on the whole window, then compare to your buttons, or you could walk through your buttons and ask the gesture where it is with respect to each button.

Probably best would be to subclass UIButton and make each button itself the target; then you know exactly what view you're in.

0

精彩评论

暂无评论...
验证码 换一张
取 消