2013-10-16 22 views
1

我正在学习iOS开发,我在看UIGestureRecognizer的。关于UIGestureRecognizers

我有一个看法。当您点击该视图时,我想要显示一个UIPopoverController,我也希望它像UIButton那样工作,因为它在按下时突出显示。

我想做到这一点的方法是使用2 UIGestureRecognizer的 - 一个UITapGestureRecognizerUILongPressGestureRecognizer

我遇到的问题是亮点方法立即调用(我想),但如果我然后移动我的手指足够远,UITapGestureRecognizer被取消。此时,我想调用另一种方法(unhighlight)来恢复UIView的初始背景颜色,但我在如何执行此操作时已丢失。

我对此很新,所以这个问题可能很基本,我很感谢任何人都可以给我的帮助。

UIViewController

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(togglePopover)]; 

[self.view addGestureRecognizer:tap]; 

UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(highlight)]; 
press.minimumPressDuration = 0.f; //highlight immediately 
press.delegate = self; //set the delegate to self 
[self.view addGestureRecognizer:highlight]; 


//the delegate part of the UIViewController 
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldRecognizeSimultaneouslyWithOtherGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer { 
    return YES; //allows allow simultaneous recognition of gestures on this view 
} 
+0

如果你希望视图像一个按钮,那为什么不使用'UIButton'? – rmaddy

+0

好点,我当然可以(也可能会) - 我希望在提问这个问题的过程中,更多地了解一下'UIGestureRecognizer'。 – Adam

+0

@rmaddy - 如果你让你的评论更像答案,并给出答案,我会接受它。你是对的,我应该只使用'UIButton' - 我已经这样做了,它正在按照我的需要工作。 – Adam

回答

0

如果您希望的行为类似于UIButton,为什么不能只使用UIButton

否则,您必须在目标方法内捕获手势的状态。在为手势识别器声明动作目标时,确保在目标名称后面加上冒号。

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(togglePopover:)]; 

现在,里面-togglePopover,读通过手势识别的state财产。 That is documented here。您正在寻找国家UIGestureRecognizerStateCancelled

1

一个UITapGestureRecognizer具有给定的行为,你已经在你的具体情况只是描述。

您可以使用像UIPanGestureRecognizer这样的连续手势识别器来完成您的工作。

具体来说,连续手势识别器动作方法将根据姿势识别器经过的状态接收一系列调用。

其中的一个状态是UIGestureRecognizerStateCancelled,因此您可以管理它以检测手势何时被取消,例如在您的情况下,并通过删除高亮显示进行相应操作。另一方面,当您的动作在UIGestureRecognizerStateBegan状态下被调用时,您会突出显示该按钮。

你的操作方法是这样的:

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer { 

    if (recognizer.state == UIGestureRecognizerStateBegan) { 

    ... 
    } else if (recognizer.state == UIGestureRecognizerStateCancelled) { 

    ... 
    } 
} 

另一种方法完全将创建自己的手势识别器子类,在那里你会处理touchesBegan:/touchesMoved:/touchesEnded:方法,以满足您的需求。

如果你看看UIGestureRecognizer reference,你会发现很多信息。

+0

如何检测UIGestureRecognizer何时转换为UIGestureRecognizerStateCancelled?看起来像一个基本问题,但我似乎无法在Apple Developer文档中找到答案。我可以使用KVO吗? – Adam

+0

您不能使用水龙头识别器。泛识别器动作将接收所有相关的呼叫,因为它是连续的识别器。看到我编辑的答案... – sergio