IOS touch tracking code -
i'm making app iphone in xcode, , requires box follow finger on x axis. couldn't find solution online this, , coding knowledge isn't great.
i've been trying use touchesbegan , touchesmoved.
could please write me code please?
first need uigesturerecognizerdelegate on viewcontroller.h file:
@interface viewcontroller : uiviewcontroller <uigesturerecognizerdelegate> @end then declare uiimageview on viewcontroller.m, so, bool track if touch event occurring inside uiimageview:
@interface viewcontroller () { uiimageview *ballimage; bool touchstarted; } then initialize 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 can start doing modifications what's best 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 need move on x axis // comment following line: center.y += p1.y - p0.y; ballimage.center = center; nslog(@"moving uiimageview..."); } }
Comments
Post a Comment