如果检测到超出范围,则禁用平移手势
Posted
技术标签:
【中文标题】如果检测到超出范围,则禁用平移手势【英文标题】:Disabling Pan Gesture if out of bounds detected 【发布时间】:2012-12-14 14:53:41 【问题描述】:我有一个 UIView 我正在尝试在屏幕上上下移动,但是我只想让它平移,这样当它处于正常位置 (0, 0) 时你不能向下拖动视图
我试图检测识别器的中心何时不是视图高度的一半,但是视图是不可移动的,并且中心始终是高度的一半(在本例中为 230)。
有什么想法吗?
- (IBAction)panDetected:(UIPanGestureRecognizer *)recognizer
CGPoint translation = [recognizer translationInView:self.view];
NSLog(@"\ncenter.y: %f\ntranslation.y: %f\n", recognizer.view.center.y, translation.y);
if (recognizer.view.center.y > ([[UIScreen mainScreen] bounds].size.height - 20)/2)
return;
recognizer.view.center = CGPointMake(recognizer.view.center.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
【问题讨论】:
recognizer.view.center = CGPointMake(recognizer.view.center.x, MAX(recognizer.view.center.y + translation.y, 230)); 【参考方案1】:不要手动计算点是否在视图的范围内,而是使用CGRectContainsPoint(rect, point)
。这对我有用,我喜欢它,因为它更短且更具可读性:
func handlePan(pan: UIPanGestureRecognizer)
switch pan.state
case .Began:
if CGRectContainsPoint(self.pannableView.frame, pan.locationInView(self.pannableView))
// Gesture started inside the pannable view. Do your thing.
【讨论】:
【参考方案2】:CGPoint translation = [recognizer translationInView:self.view];
CGPoint finalpoint = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y+ translation.y);
//limit the boundary
if ((recognizer.view.frame.origin.x>0 && translation.x > 0) || (recognizer.view.frame.origin.x + recognizer.view.frame.size.width<=320 && translation.x < 0))
finalpoint.x = recognizer.view.center.x;
if ((recognizer.view.frame.origin.y>0 && translation.y > 0) || (recognizer.view.frame.origin.y + recognizer.view.frame.size.height<=self.view.frame.size.height && translation.y < 0))
finalpoint.y = recognizer.view.center.y;
//set final position
recognizer.view.center = finalpoint;
[recognizer setTranslation:CGPointZero inView:self.view];
【讨论】:
【参考方案3】:试试
CGPoint translation = [recognizer translationInView:self.view];
if (translation.x+recognizer.view.frame.origin.x<0||translation.y+recognizer.view.frame.origin.y<0)
return;
recognizer.view.center = CGPointMake(recognizer.view.center.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
【讨论】:
【参考方案4】:recognizer.view.center = CGPointMake(recognizer.view.center.x, MAX(recognizer.view.center.y + translation.y, ([[UIScreen mainScreen] bounds].size.height - 20)/2));
【讨论】:
以上是关于如果检测到超出范围,则禁用平移手势的主要内容,如果未能解决你的问题,请参考以下文章
检测 CGAffineTransformed 视图是不是超出屏幕/UIView 的范围