14

我的简单故事板 IPad 项目中有 UIViewController,其中包含放置在整个表面 (1024 x 768) 上的 UIScrollView。我创建了 3 个 XIB 文件,它们是我的应用程序在 viewDidLoad 启动时加载的 UIView,并将它们添加到 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;

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

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

  • 触摸 UIScrollView 组件
  • 触摸 UIScrollView 内的 UIView 中的 UIButton(如果触摸此按钮)

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

我认为解决方案是以某种方式对 UIScrollView 内的 UIView 中的组件进行的触摸应该发送到 UIViewControllerClass,但我没有找到这样做的方法。

如果有人可以帮助我,我将不胜感激。提前致谢。


[编辑#1:郑的回答]

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

对于我上面的例子,这条线解决了所有问题:

touch.cancelsTouchesInView = NO;

非常感谢郑。

4

3 回答 3

18

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

关闭 UIScrollView 中的键盘

这个想法是告诉滚动视图不要吞下滚动视图区域内的所有点击手势。

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

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];
}
于 2012-09-03T08:55:10.133 回答
3

您可以继承您的 UIScrollView 并覆盖- hitTest:withEvent:系统调用的方法以确定哪个视图将处理事件。每当调用它时,您都可以假设滚动视图内部发生了触摸事件,并且通过调用超级实现,您可以获得通常会处理该事件的视图。

于 2012-09-03T08:10:50.533 回答
0

您可以在 UIscrollView 中捕获任何类型的手势。确保您还处理了一些默认属性,例如将 cancelsTouchesInView 属性设置为 false,默认情况下为 true。还要为您的子视图提供一些标签号,以在选择器中进行区分。& 还使他们的用户交互成为真实。

让点击 = UITapGestureRecognizer(目标:自我,动作:

选择器(didTapByUser(_:)))

于 2017-05-01T18:14:10.780 回答