I am trying to create a control where a user can touch and move a button within a frame. Here is my code.
- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
UITouch *touch = [[event touchesForView:button] anyObject];
// get delta
CGPoint previousLocation = [touch previousLocationInView:button];
CGPoint location = [touch locationInView:button];
CGFloat delta_x = location.x - previousLocation.x;
CGFloat delta_y = location.y - previousLocation.y;
// move button
button.center = CGPointMake(button.center.x + delta_x,
button.center.y + delta_y);
}
I am able to move the button(by touching and dragging), but how to restrict the button, so that it can move only left/right within a rectangle frame.
Perhaps this method will help you. I used it in a simple pong game I made a while ago. It is for a UIView that is the bounce pad for the pong game. I have restricted the movement of the bounce pad to the x-direction and not outside of the screen bounds.
If something ain’t clear write a comment and I’ll try to explain.