Bad_Developer
Bad_Developer

Reputation: 537

Move an uiview when a button is moving

I'm writing a custom UIButton that can draggable around the screen. When I press this button, a uiview will bee added into superview. I've adding pan gesture for this view so it's can draggable too. And now I wanna make both uiview and button can draggable at the same time. How can I do that?
For example:

Upvotes: 0

Views: 116

Answers (2)

user3182143
user3182143

Reputation: 9589

I tried the sample code for your application.It works perfectly.When you drag button,the view also moves simultaneously.

First I created button and UIView.I hooked up that.

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIButton *btnDragg;
- (IBAction)actionDragg:(id)sender;
@property (strong, nonatomic) IBOutlet UIView *viewDrag;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


@synthesize btnDragg,viewDrag;

- (void)viewDidLoad 
{
   [super viewDidLoad];
   // Do any additional setup after loading the view, typically from a nib.
   UIPanGestureRecognizer *panRecognizer;
   panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(wasDragged:)];
   panRecognizer.cancelsTouchesInView = YES;
   [btnDragg addGestureRecognizer:panRecognizer];
}


- (void)wasDragged:(UIPanGestureRecognizer *)recognizer
{
   UIButton *button = (UIButton *)recognizer.view;

   CGPoint translation = [recognizer translationInView:button];
   CGPoint translationView = [recognizer translationInView:viewDrag];
   button.center = CGPointMake(button.center.x + translation.x, button.center.y + translation.y);
   viewDrag.center = CGPointMake(viewDrag.center.x + translationView.x, viewDrag.center.y + translationView.y);

   [recognizer setTranslation:CGPointZero inView:button];
   [recognizer setTranslation:CGPointZero inView:viewDrag];
}

Before I drag the button,it is in original positionenter image description here

Then When I drag the button,the view also moves with button.Now it changes the position after the I drag the button.enter image description here

Upvotes: 0

Florian Burel
Florian Burel

Reputation: 3456

I would encapsulate the button and the view in a parent transparent UIView. Add the pan gesture to it and move it around... both will then move.

Upvotes: 1

Related Questions