This is tutorial how to drag the circle on screen with iOS touch API
iOS has very powerful Touch API, and you can do lots of cool stuff with them.
1. How to setup Touch API in your View
2. How to use touchesMoved method to move circle around the view
Let's jump into it.
In order to get the touches events, you need to override two methods in your View:
touchesBegan
touchesMoved
touchesBegan is called when your finger touches the screen initially
touchesMoved is called when your finger is moving across the screen
when you touch location [1, 2] and move your finger to [3, 5]
1. touchesBegan is called at CGPoint [1, 2]
2. touchesMoved is called at CGPoint [3, 5]
Note: touchesMoved will be called many times after touchesBegan
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"%s", __PRETTY_FUNCTION__);
UITouch* touch = [touches anyObject];
if(touch != nil){
_initXY = [touch locationInView:touch.view];
}
}
From above code in touchesBegan, CGPoint _initXY will be [1, 2]
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch* touch = [touches anyObject];
if(touch != nil){
CGPoint currXY = [touch locationInView:touch.view];
_center.x = _center.x + (currXY.x - _initXY.x);
_center.y = _center.y + (currXY.y - _initXY.y);
_initXY = currXY;
}
}
When touchesMoved is called, CGPoint currXY will be [3, 5].
So we add the differences to the center of circle: CGPoint _center
Finally we update the _initXY to currXY: _initXY = currXY
so when the next touchesMoved is called, _initXY will be the previous touchesMoved location