IOS触摸跟踪代码

时间:2014-04-18 02:11:06

标签: ios touch tracking

我在Xcode中为iPhone制作应用程序,它需要一个盒子才能在X轴上跟随我的手指。我无法在网上找到任何解决方案,而且我的编码知识也不是很好。

我一直在尝试使用 touchesBegan touchesMoved

有人可以请给我写一些代码吗?

1 个答案:

答案 0 :(得分:1)

首先,您需要 ViewController.h 文件中的UIGestureRecognizerDelegate

@interface ViewController : UIViewController <UIGestureRecognizerDelegate>

@end

然后您在 ViewController.m 上声明UIImageView,就像这样,使用BOOL来跟踪UIImageView内是否发生了触摸事件:

@interface ViewController () {
    UIImageView *ballImage;
    BOOL touchStarted;
}

然后,您在UIImageView上初始化viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *image = [UIImage imageNamed:@"ball.png"];
    ballImage =  [[UIImageView alloc]initWithImage:image];
    [ballImage setFrame:CGRectMake(self.view.center.x, self.view.center.y, ballImage.frame.size.width, ballImage.frame.size.height)];
    [self.view addSubview:ballImage];
}

之后,您可以使用以下方法开始修改最适合您的方法:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touch_point = [touch locationInView:ballImage];

    if ([ballImage pointInside:touch_point withEvent:event])
    {
        touchStarted = YES;

    } else {

        touchStarted = NO;
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if ([touches count]==1 && touchStarted) {
        UITouch *touch = [touches anyObject];
        CGPoint p0 = [touch previousLocationInView:ballImage];
        CGPoint p1 = [touch locationInView:ballImage];
        CGPoint center = ballImage.center;
        center.x += p1.x - p0.x;
        // if you need to move only on the x axis
        // comment the following line:
        center.y += p1.y - p0.y; 
        ballImage.center = center;
        NSLog(@"moving UIImageView...");
    }

}