iOS - 背景视图正在消耗触摸事件

iOS - Background view is consuming touch events

我将从描述屏幕的外观开始。 UIPageViewController 覆盖了 100% 的屏幕,UIView (在页面顶部 vc) 覆盖了 20% 的屏幕屏幕。容易,对吧?基本上UIView结束了UIPageViewController.

因此,我使用 self.view.addSubview(pageVC.view) 以编程方式将 UIPageViewController 添加到我的视图控制器中。但是 UIView 是在 界面生成器

中定义的

因此,由于 UIPageViewController 最后添加,它覆盖了 UIView,这迫使我调用 myUIView.layer.zPosition = 1,以便 UIView 可见。

问题是 UIView 上的任何触摸都会被 UIPageViewController 消耗掉。我该如何解决这个问题?

特定视图的层 属性 仅用于渲染该特定视图。这就是为什么对层的更改不会影响与该特定视图的交互的任何内容的原因。

但是,UIView 上的 -sendSubviewToBack:-bringSubviewToFront: 方法旨在实现您正在寻找的内容。在这里你可以为他们阅读docs

我写这段代码是为了让你测试这个方法在做什么。尝试 comment/uncomment 最后一行或更改添加子视图的顺序,以更好地了解其工作原理。

UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(200, 200, 100, 100)];
UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(200, 200, 150, 150)];

firstView.backgroundColor = [UIColor greenColor];
secondView.backgroundColor = [UIColor redColor];

[self.view addSubview:firstView];
[self.view addSubview:secondView];

UITapGestureRecognizer *firstTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(firstTap)];
UITapGestureRecognizer *secondTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(secondTap)];
[firstView addGestureRecognizer:firstTap];
[secondView addGestureRecognizer:secondTap];

[self.view sendSubviewToBack:secondView];