检测UIScrollView上的触摸事件和UIView的组件[放在UIScrollView中]

uer*_*ceg 13 uiscrollview ios uitapgesturerecognizer

我在我的简单故事板IPad项目上有UIViewController,它包含放置在整个表面(1024 x 768)上的UIScrollView.我创建了3个XIB文件,这些文件是我的应用程序在viewDidLoad中启动时加载的UIViews,并将它们添加到UIScrollView中.这3个XIB文件中的每一个只包含一个UIButton.

这是层次结构:

~UIViewController(UIViewControllerClass是这个UIViewController的类)

~~ UIScrollView(包含3个相同的UIViews)

~~~ UIView(UIViewClass是此XIB文件的文件所有者)

~~~~ UIButton

我希望我的UIViewControllerClass能够识别两者:触摸UIScrollView组件上的任何位置,如果触摸了UIScrollView,如果触摸了UIScrollView中UIView内的UIButton,则可以获得完全触摸该按钮的信息.

我在UIViewClass中创建了IBAction,用于触摸UIScrollView中UIView内的UIButton,当我在所有元素(UIViewController,UIView和UIScrollView)上设置User Interaction Enabled = YES时,会调用此方法.

但此时我的UIViewControllerClass并不知道在UIButton上的UIScrollView内发生了触摸.我做了这样的触摸识别器:

UITapGestureRecognizer *touch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTouch)];
touch.numberOfTouchesRequired = 1;
Run Code Online (Sandbox Code Playgroud)

并将其添加到UIScrollView组件.通过这种方式,我能够在UIViewControllerClass中检测UIScrollView组件上的触摸事件,但是UIView中的UIButton触摸事件处理程序不再被调用.

所以,我需要在UIViewControllerClass中有这两个信息:

  • 触摸UIScrollView组件
  • 触摸UIVut中的UIButton,它位于UIScrollView内(如果触摸了此按钮)

我认为将触摸事件识别器附加到整个UIScrollView组件不是解决方案,因为它禁用了我在UIViewClass中编写的所有触摸事件处理程序.

我认为解决方案是,在UIScrollView中的UIView组件上进行的某些操作应该发送到UIViewControllerClass,但我没有找到一种方法来执行此操作.

如果有人能帮助我,我会非常感激.提前致谢.


[编辑#1:郑的回答]

点击手势必须将cancelsTouchesInView选项设置为NO!

对于我的上述情况,这条线解决了一切:

touch.cancelsTouchesInView = NO;
Run Code Online (Sandbox Code Playgroud)

非常感谢郑.

Zha*_*ang 18

我不知道这是否适合你,但我在这里给出了关于scrollview中视图的触摸事件的答案:

在UIScrollView中关闭键盘

我们的想法是告诉scrollView不要吞下滚动视图区域内的所有点击手势.

我会在这里粘贴代码,希望它能解决你的问题:

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];

// prevents the scroll view from swallowing up the touch event of child buttons
tapGesture.cancelsTouchesInView = NO;    

[pageScrollView addGestureRecognizer:tapGesture];

[tapGesture release];

...

// method to hide keyboard when user taps on a scrollview
-(void)hideKeyboard
{
    [myTextFieldInScrollView resignFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)