我遇到了 UIPanGestureRecognizer 的问题。假设我在添加第一个按钮时使用不同的标签动态添加 10 个按钮,然后尝试将其拖到其他地方,然后它可以正常工作。然后,如果我添加其他按钮,然后尝试拖动第二个按钮,那么它甚至可以正常工作,但是如果那时我会拖动第一个按钮,那么它不会被拖动。日志中显示的消息是忽略对 [UIPanGestureRecognizer setTranslation:inView:] 的调用,因为手势识别器未激活。手势仅适用于最近添加的按钮。下面是我正在使用的代码
这是添加按钮的代码
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];
这是手势代码
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];