Big Box Developer
Big Box Developer

Reputation: 137

How to add a UIPanGestureRecognizer programmatically

In my app, you can touch the screen and an editable UITextField appears on the screen. I want to be able to move these newly added UITextFields around the screen. I would also like to add a rotation gesture and a pinch gesture. This is very difficult to do right now, because every time the screen is tapped a new SubView is added (UITextField). Below is my coding:

- (IBAction)addText:(UITapGestureRecognizer *)recognizer 
{ 
   if (recognizer.state == UIGestureRecognizerStateEnded) 
   {       
        UITextField *newText = [[UITextField alloc] initWithFrame:CGRectMake(40, 205, 280, 128)];
        newText.hidden = NO;
        [self.view addSubview:newText];
        newText.text = @"phrase";
        [newText setFont:[UIFont fontWithName:@"ArialRoundedMTBold" size:60]];
        newText.borderStyle = UITextBorderStyleNone;
        UIPanGestureRecognizer *pan= [[UIPanGestureRecognizer alloc] initWithTarget:newText action:nil];

        CGPoint translation = [pan translationInView:newText];
        pan.view.center = CGPointMake(pan.view.center.x + translation.x, pan.view.center.y + translation.y);
        [pan setTranslation:CGPointMake(0,0) inView:self.view];
     }
}

Upvotes: 0

Views: 1932

Answers (1)

rob mayoff
rob mayoff

Reputation: 385590

There are a few ways to set up dependencies between gesture recognizers. One way which seems useful here is the requireGestureRecognizerToFail: method. After you create the pan recognizer, add this:

[recognizer requireGestureRecognizerToFail:pan];

Now the tap recognizer (in the recognizer variable) won't activate unless the pan recognizer has decided that the user is not panning.

Upvotes: 1

Related Questions