问题
I have an UIButton
and I want to move that button by touching and swiping it in the screen. When I release the touch it will be in the current position. Explain clearly, please.
回答1:
You can move a view by using touch moved event. There is a sample tutorial MoveMe by Apple which drags a view and after releasing the touch animate the view. Check specially the touch events (touchesBegan, touchesMoved, touchesEnded) in MoveMeView.m to get the idea how they have moved placardView. You can move your button just like the placardView.
Taken from 'drag' move a uibutton so it acts like uiScrollView
回答2:
check this
you should make move frame from the points and move frame accordingly so that your button moves in places of touches
回答3:
If you are scripting for iOS 3.2 and above, consider using UIPanGestureRecognizer
.
Simply attach an instance of it like this,
...
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
panGesture.maximumNumberOfTouches = 1;
panGesture.minimumNumberOfTouches = 1;
[self.button addGestureRecognizer:panGesture];
[panGesture release];
...
and define handlePan:
like this,
- (void)handlePan:(UIPanGestureRecognizer *)panGesture {
CGRect buttonFrame = self.button.frame;
CGPoint translation = [panGesture translationInView:panGesture.view];
buttonFrame.origin.x += translation.x;
buttonFrame.origin.y += translation.y;
[panGesture setTranslation:CGPointMake(0, 0) inView:panGesture.view];
self.button.frame = buttonFrame;
}
来源:https://stackoverflow.com/questions/6028879/move-a-button-in-the-screen