IOS touch tracking code

你离开我真会死。 提交于 2020-01-06 20:36:18

问题


I'm making an app for iPhone in Xcode, and It requires a box to follow my finger only on the X axis. I couldn't find any solution online to this, and my coding knowledge isn't that great.

I've been trying to use touchesBegan and touchesMoved.

Could someone please write me up some code please?


回答1:


First you need the UIGestureRecognizerDelegate on your ViewController.h file:

@interface ViewController : UIViewController <UIGestureRecognizerDelegate>

@end

Then you declare an UIImageView on your ViewController.m, like so, with a BOOL to track if a touch event is occurring inside your UIImageView:

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

Then you initialize the UIImageView on 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];
}

After that you can start doing your modifications to what's best for you using these methods:

-(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...");
    }

} 


来源:https://stackoverflow.com/questions/23146367/ios-touch-tracking-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!