KsK
KsK

Reputation: 675

UIPanGestureRecognizer not works on button

I am facing problem with UIPanGestureRecognizer. suppose i am adding 10 button dynamicaly using diffrent tags when i add first button the try to drag it to other place then its works fine. and then if i add other button then try to drag that second button then even its works fine but if then i would lyk to drag first button then it not being draged and. and message shown in log is Ignoring call to [UIPanGestureRecognizer setTranslation:inView:] since gesture recognizer is not active. gesture is working only on recently added button. below is the code that i am using


Here is code to add buttons

    NSUInteger counter = 1;
    if([ButtonArray count] !=0 ){
        NSLog(@"%d",[ButtonArray count]);
        NSLog(@"hi");
        counter = [ButtonArray count] + 1;

    }
    [ButtonArray addObject:[NSString stringWithFormat:@"%d",counter]];
    NSLog(@"%d",1);
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setTag:counter];
    btn.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    //[btn addTarget:self action:@selector(Dragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
    //[self.view addSubview:btn];
    btn.userInteractionEnabled = YES;

    gesture = [[UIPanGestureRecognizer alloc] 
                                        initWithTarget:self 
                                        action:@selector(labelDragged:)];
    [btn addGestureRecognizer:gesture];
    // add it

[self.view addSubview:btn];

here is code for gesture

    UIButton *button = (UIButton *)gesture.view;

CGPoint translation = [gesture translationInView:button];


// move button
button.center = CGPointMake(button.center.x + translation.x, 
                           button.center.y + translation.y);

// reset translation
[gesture setTranslation:CGPointZero inView:button];

Upvotes: 0

Views: 1577

Answers (1)

sergio
sergio

Reputation: 69027

I suspect the problem comes down to this:

gesture = [[UIPanGestureRecognizer alloc] 
                                    initWithTarget:self 
                                    action:@selector(labelDragged:)];

I tend to think from your code that gesture is some property in your class. In this case you are constantly overriding the old gesture when you create a new one. That would also explain the behavior you describe.

EDIT:

you do not strictly need to store your gesture recognizers in a property; it would be enough to do:

UIPanGestureRecognizer* localgesture = [[UIPanGestureRecognizer alloc] 
                                    initWithTarget:self 
                                    action:@selector(labelDragged:)];
[btn addGestureRecognizer:localgesture];

then, when the labelDragged method is called, you can use its recognizer argument to know which gesture recognizers fired:

- (void)labelDragged:(UIGestureRecognizer *)gestureRecognizer;

Upvotes: 1

Related Questions