【问题标题】:iPhone - UIScrollView... detecting the coordinates of a touch [duplicate]iPhone - UIScrollView ...检测触摸的坐标[重复]
【发布时间】:2011-12-16 19:50:17
【问题描述】:

可能重复:
UIScrollview getting touch events

是否可以检测到手指在 UIScrollView 中触摸的位置?

我的意思是,假设用户以这种方式使用他的手指:点击并滚动,再次抬起手指,点击和滚动等。是否有可能知道与 self.view 相关的点击发生的 CGPoint卷轴在?滚动条占据了整个 self.view。

谢谢。

【问题讨论】:

    标签: iphone ios cocoa-touch ipad uiscrollview


    【解决方案1】:

    您可以使用手势识别器来做到这一点。要检测单击位置,请使用UITapGestureRecognizer

    UITapGestureRecognizer *tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)] autorelease];
    [myScrollView addGestureRecognizer:tapRecognizer];
    
    - (void)tapAction:(UITapGestureRecognizer*)sender{ 
        CGPoint tapPoint = [sender locationInView:myScrollView];
        CGPoint tapPointInView = [myScrollView convertPoint:tapPoint toView:self.view];
    }
    

    要将 tapPoint 转换为 self.view,您可以在 UIView 类中使用 convertPoint:toView: 方法

    【讨论】:

    • 不。如果我点击而不滚动,就会触发 tapAction。如果我确实像我说的那样轻按、滚动、抬起手指、轻按、滚动、抬起手指等,则不会检测到轻按。如果滚动条在大滑动后也滚动,也不会检测到点击。滚动条必须是静止的,并且必须进行一次干燥的水龙头才能工作。
    • 还有很多其他的手势识别器——UIPanGestureRecognizer、UIPinchGestureRecognizer、UISwipeGestureRecognizer、UIRotationGestureRecognizer。此外,您可以创建自定义识别器来检测非常复杂的触摸。我用简单的触摸举了一个更流行的例子。
    • @RubberDuck 你知道了吗?我在同一条船上...我正在开发 UICollectionView,我想检测手指触摸是否在单元格视图上
    • 我的框架下有UIkit.framework,但我找不到UITapGestureRecognizer。当我尝试写 UITapGestureRecognizer 时,它给了我未找到的错误。
    • @beryllium 为什么你不只是做 [sender locationInView: myScrollView] ?
    【解决方案2】:

    您可以在视图中找到位置并将滚动设置添加到它。现在,您的下一个问题是不会调用-(void)touchesBegan:touches:event,因为事件将被发送到您的滚动视图。这可以通过继承您的 UIScrollView 并让滚动视图将触摸事件发送到下一个响应者(您的视图)来解决。

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        // Position of touch in view
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint touchPoint = [touch locationInView:self.view];
    
        // Scroll view offset
        CGPoint offset = scrollView.contentOffset;
    
        // Result
        CGPoint scrollViewPoint = CGPointMake(touchPoint.x, touchPoint.y + offset.y);
        NSLog(@"Touch position in scroll view: %f %f", scrollViewPoint.x, scrollViewPoint.y);
    }
    

    【讨论】:

    • 不。如果我点击而不滚动,就会触发 touchesBegan。如果我确实像我说的那样轻按、滚动、抬起手指、轻按、滚动、抬起手指等,则不会检测到轻按。如果滚动条在大滑动后也滚动,也不会检测到点击。滚动条必须保持静止,并且必须进行一次干燥的水龙头,才能使其正常工作。看起来并不容易。
    【解决方案3】:

    【讨论】:

    • 这并不容易。如果滚动视图仍然在移动,TouchesBegan 只会检测到触摸,如果它已经在移动并且我触摸它,touchesBegan 将不会检测到任何东西。
    【解决方案4】:

    看看touchesBegan:withEvent:,你会得到一个UITouch's的NSSet,一个UITouch包含一个locationInView:方法,它应该返回触摸的CGPoint。

    【讨论】:

    • 在这种情况下你需要继承 UIScrollView
    猜你喜欢
    • 1970-01-01
    • 2016-10-16
    • 2016-02-06
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多