Azik
Azik

Reputation: 1

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.

Upvotes: 0

Views: 812

Answers (3)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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

Upvotes: 1

Narayanan Ramamoorthy
Narayanan Ramamoorthy

Reputation: 826

check this

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

Upvotes: 2

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31730

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

Upvotes: 2

Related Questions