jireh
jireh

Reputation: 89

How to change the positions of UIButton on iOS/iPhone

In my application, I am creating three UIButton inside, and I want these button should be swapped among it. (i.e) If I drag and drop the (button 1) and place it on (button 2), then (button 2) should get replaced in the position of (button 1) and also the same for (button 3). I found, for how to drag and drop the UIButton, but I can't able to swap it.

Here is my code for button creation and drag and drop:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"Drag One!" forState:UIControlStateNormal];

    // add drag listener
    [button addTarget:self action:@selector(wasDragged:withEvent:) 
     forControlEvents:UIControlEventTouchDragInside];

    // center and size
    button.frame = CGRectMake((self.view.bounds.size.width - 10)/2.0,
                              (self.view.bounds.size.height - 50)/2.0,
                              100, 50);
    button.tag=0;
    [self.view addSubview:button];
   .........


  -(void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{

 if(button.tag==0){


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

Upvotes: 0

Views: 860

Answers (1)

Guru
Guru

Reputation: 22042

Use code like this:

[UIView animateWithDuration:0.5
                              delay:0.1
                            options: UIViewAnimationCurveEaseOut
                         animations:^
         {
             CGSize s = [[CCDirector sharedDirector] winSize];

             CGRect frame = mButton.frame;
             frame.origin.y = location.y ;
             frame.origin.x = location.x ;
             mButton.frame = frame;
         } 
                         completion:^(BOOL finished)
         {


         }];

Upvotes: 1

Related Questions