【问题标题】:How to attach one UIPanGestureRecognizer object for several views?如何为多个视图附加一个 UIPanGestureRecognizer 对象?
【发布时间】:2011-10-28 12:44:40
【问题描述】:

是否可以只分配一个 UIPanGestureRecognizer 并附加到多个视图?我有多个用户可以移动(平移)的屏幕 UIImageView 对象。如果我正在分配并将相同的 UIPanGestureRecognizer 对象附加到所有视图,则平移手势仅适用于最后一个附加视图。我通过对 UIPanGestureRecognizer 进行多个分配/初始化来解决问题,我的意思是每个视图都有一个不同的 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];

  ...

PS。我还启用了 MultipleTouchEnabled 和 UserInteractionEnabled。还有更优雅的解决方案吗?

【问题讨论】:

    标签: iphone objective-c uigesturerecognizer


    【解决方案1】:

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

    我建议在方法中创建手势识别器:

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

    然后只是做

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

    【讨论】:

    • 该解决方案虽然在技术上是正确的,但并不总是有效 - 例如,如果您要移动多个重叠视图并且需要将触摸发送到不在堆栈顶部的视图.相反,可以将单个手势识别器附加到多个目标视图的父视图,并将手势委托给正确的视图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    相关资源
    最近更新 更多