获取UIGestureRecognizer事件并获取根容器视图的最佳方法是什么?

时间:2016-10-05 23:53:36

标签: ios objective-c uiviewcontroller

我有一个UIViewController,我在其中添加了一堆UIViews作为子视图。然后我将UIGestureRecognizer附加到每个,所以我可以在点击时收到通知。这是UIViewController中的代码:

- (void)attachSubview{
  UIImageView *childView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"child"]] ;
  UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
  [childView addGestureRecognizer:singleFingerTap];
  [self.view addSubView childView];
}

- (void)tapped:(UITapGestureRecognizer *)recognizer{
  NSLog(@"Tapped view : %@", recognizer.view);
  NSLog(@"The root view is : %@", self.view);
}

现在,问题在于:我实际上想要将这两种方法提取到一个单独的类中。在这种情况下,我无法在self.view方法中使用tapped:,因为自己不再是viewcontroller类。

所以我想要一个简单而有效的方法来获取识别器对象并以某种方式获得图像视图所属的根视图。这样做的最佳和未来证明方法是什么?

1 个答案:

答案 0 :(得分:0)

你能试试吗?

- (void)viewDidLoad {
   [super viewDidLoad];
   //example of its use. You can replace with [className attachSubview:self.view] for example
   self.view = [self attachSubview:self.view];
}

- (UIView *)attachSubview:(UIView *)passedInView{
   UIImageView *childView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"child"]] ;
   UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
   [childView addGestureRecognizer:singleFingerTap];
   [passedInView addSubview:passedInView];
   return passedInView;
}

- (void)tapped:(UITapGestureRecognizer *)recognizer{
   NSLog(@"Tapped view : %@", recognizer.view);
   NSLog(@"The root view is : %@", recognizer.view.superview);
}