简体   繁体   English

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

[英]How to attach one UIPanGestureRecognizer object for several views?

Is it possible to alloc only one UIPanGestureRecognizer and attach to multiple views? 是否可以仅分配一个UIPanGestureRecognizer并附加到多个视图? I have multiple on-screen UIImageView objects that user can move (pan). 我有多个屏幕上的UIImageView对象,用户可以移动(平移)对象。 If I'm making alloc and attaching the same UIPanGestureRecognizer object to all views then the pan gesture works only on the last attached view. 如果我正在分配并将相同的UIPanGestureRecognizer对象附加到所有视图,则平移手势仅在最后一个附加的视图上起作用。 I did a workaround by making multiple alloc/init of UIPanGestureRecognizer, I mean one different UIPanGestureRecognizer object for each view. 我通过对UIPanGestureRecognizer进行多个alloc / init来实现了解决方法,我的意思是每个视图都使用一个不同的UIPanGestureRecognizer对象。 Here's the code: 这是代码:

- (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];

  ...

PS. PS。 I also have enabled MultipleTouchEnabled & UserInteractionEnabled. 我还启用了MultipleTouchEnabled和UserInteractionEnabled。 Are there any more elegant solutions? 还有更优雅的解决方案吗?

No - each UIGestureRecognizer can only belong to one view. 否-每个UIGestureRecognizer只能属于一个视图。 Just create multiple with the same properties and assign them to the different views. 只需创建具有相同属性的多个并将它们分配给不同的视图即可。

I suggest creating the gesture recognizer in a method: 我建议在一种方法中创建手势识别器:

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

and then just doing 然后做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM