问题描述
我的问题的简短版本:
我不知道如何让我的 UITapGestureRecognizer 的动作"采用额外的参数,并实际使用它们.
I cannot figure out how to make the "action" for my UITapGestureRecognizer take additional parameters, and actually use them.
这是我的问题的概要:
我试图让我的 iPad 应用程序记录(使用 NSLog)每当他们按下我的应用程序的 UIButtons 时发生的 UITouch 的坐标.触摸的位置需要相对于被触摸的按钮.
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 relative to the button that was touched.
我做了什么:
我已经实现了一个 UITapGestureRecognizer 并将它添加到我的每个按钮中.我的问题在于要使用的操作,因为它需要对每个按钮都是动态的.
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.
我目前有这个代码:
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];
当我知道这可行时,我将使用 for 循环将 iconClickRecognizer 添加到所有按钮的标签.
When I know that this works, I will use a for-loop to add the iconClickRecognizer to all of the buttons by their tag.
logIcon:(int)withTag 方法如下所示:
-(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);
}
什么不起作用:
当我将标签硬编码到 logIcon 方法中时,它会正确记录信息.但是,我不知道如何使这个方法动态化,并且实际上使用了tag"参数.
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.
任何帮助将不胜感激.
谢谢,亚历克斯
推荐答案
UIGestureRecognizer 类的文档指定操作必须是以下形式:
The docs for UIGestureRecognizer class specify that the action must be of the form:
- (void)handleGesture;
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;
不是你的形式:
- (void)logIcon:(UIGestureRecognizer *)gestureRecognizer withTag:(int)tag
因此您可以询问gestureRecognizer它在整个窗口中的位置,然后与您的按钮进行比较,或者您可以遍历您的按钮并询问手势相对于每个按钮的位置.
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.
最好的办法是继承 UIButton 并使每个按钮本身成为目标;那么你就知道你在哪个视图中了.
Probably best would be to subclass UIButton and make each button itself the target; then you know exactly what view you're in.
这篇关于UIGestureRecognizers 的自定义操作(带有自定义参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!