Iphone 如何为多个视图附加一个UIPanGestureRecognizer对象?

Iphone 如何为多个视图附加一个UIPanGestureRecognizer对象?,iphone,objective-c,uigesturerecognizer,Iphone,Objective C,Uigesturerecognizer,是否可以只分配一个UIPangestureRecognitor并附加到多个视图?我有多个用户可以移动(平移)的屏幕UIImageView对象。如果我正在进行alloc并将相同的UIPangestureRecognitor对象附加到所有视图,则平移手势仅适用于最后附加的视图。我通过对UIPanGestureRecognizer进行多个alloc/init来解决问题,我的意思是为每个视图创建一个不同的UIPanGestureRecognizer对象。代码如下: - (void)viewDidLoad

是否可以只分配一个UIPangestureRecognitor并附加到多个视图?我有多个用户可以移动(平移)的屏幕UIImageView对象。如果我正在进行alloc并将相同的UIPangestureRecognitor对象附加到所有视图,则平移手势仅适用于最后附加的视图。我通过对UIPanGestureRecognizer进行多个alloc/init来解决问题,我的意思是为每个视图创建一个不同的UIPanGestureRecognizer对象。代码如下:

- (void)viewDidLoad
{
  [super viewDidLoad];

  UIPanGestureRecognizer * pgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(updateImagePosition:)];
  [self.panningBtn1 addGestureRecognizer:pgr];
  [pgr release];

  pgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(updateImagePosition:)];
  [self.panningBtn2 addGestureRecognizer:pgr];
  [pgr release];

  ...

另外,我还启用了MultipleTouchEnabled和UserInteractionEnabled。是否还有更优雅的解决方案?

否-每个
UIgestureRecognitor
只能属于一个视图。只需创建具有相同属性的多个视图,并将它们指定给不同的视图

我建议使用以下方法创建手势识别器:

-(UIGestureRecognizer *)myGRMethod {
  UIPanGestureRecognizer *pgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(updateImagePosition:)];
  return [pgr autorelease];
}
然后就这么做

for (UIView *view in views) {
    [view addGestureRecognizer:[self myGRMethod]];
}

该解决方案虽然在技术上是正确的,但并不总是有效的——例如,如果您移动多个重叠视图,并且需要将触摸发送到不在堆栈顶部的视图。相反,可以将单个手势识别器附加到多个目标视图的superview,并将手势委托给正确的视图。