iOS - 如何在用户拖动时触摸的线上绘制点

标签 ios objective-c uipangesturerecognizer

我有一个矩形 View ,其中包含我以编程方式绘制的垂直细线。

这是我用来画线的代码:

- (void)drawLines
{
    CGFloat spacing = _bgView.frame.size.width / 11.0f;

    for(int i = 1; i < 11; i++)
    {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake((CGFloat)(i * spacing), 0, 1, _bgView.frame.size.height)];
        line.backgroundColor = [UIColor whiteColor];
        line.tag = i;

        [_bgView addSubview:line];
    }
}

线条由根据矩形 View (_bgView) 的宽度计算的均匀分布的空间分隔。

下面是它的概览:

enter image description here

当用户在矩形 View 中执行拖动时,当他/她的手指穿过或触摸一条线时,将在该特定点上绘制一个点。

下面的代码检测用户在线上的触摸点,并在该点上画一个点。

- (IBAction)drawDots:(id)sender
{
    UIPanGestureRecognizer *pan = (UIPanGestureRecognizer *)sender;

    CGPoint pannedPoint = [pan locationInView:_bgView];

    for (UIView *subview in _bgView.subviews)
    {
        if (CGRectContainsPoint(subview.frame, pannedPoint) && subview.tag > 0)
        {
            NSLog(@"Point x:%.2f y:%.2f TAG:%i", pannedPoint.x, pannedPoint.y, subview.tag);

            UIView *point = [[UIView alloc] initWithFrame:CGRectMake(pannedPoint.x - 2.5, pannedPoint.y - 2.5, 5, 5)];
                point.backgroundColor = [UIColor redColor];

            [_bgView addSubview:point];
        }
    }
}

现在,如果用户平移得非常快,这将是结果:

enter image description here

可以看出,只绘制了一些点,这就是为什么其他线上有很多缺失点的原因。

这应该是预期的结果:

enter image description here

但是,只有当用户平移速度过慢时才会发生这种情况。

即使用户的手指移动得非常快,我如何绘制被用户触摸截取的线上的点?

谢谢!

最佳答案

您应该使用 UIResponder 方法来检测用户触摸,而不是平移手势:

- touchesBegan:withEvent:
- touchesMoved:withEvent:
- touchesEnded:withEvent:
- touchesCancelled:withEvent:

第二种方法 - touchesMoved:withEvent: 当用户在屏幕上不断移动手指时调用,因此您可以获取手指位置:

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];    

然后只需添加您的检测逻辑即可。

查看文档了解更多详情: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/

关于iOS - 如何在用户拖动时触摸的线上绘制点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37341769/

相关文章:

ios - 如何将对象放置在中心图像周围的阵列中?

ios - 使用终端命令 'open -n -a "iOS Simulator"' 运行多个 iOS Simulator.app

ios - 通过电子邮件发送 protected PDF Objective-c

ios - 如何检测 UICollectionView 的滚动方向?

ios - 实现 Facebook Messenger 样式平移到全屏 View 类似效果

objective-c - TBXML 中的异步和 initWithURL

ios - 如何使用按钮增加/减少价格标签值?

ios - 如何在 UIView 中剪切路径?

objective-c - 蓝牙核心框架回调例程 peripheralManagerIsReadyToUpdateSubscribers : isn't called

iphone - 如何限制平移手势区域?