简体   繁体   中英

Move a button in the screen

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.

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

check this

you should make move frame from the points and move frame accordingly so that your button moves in places of touches

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM