如何获取UIPageViewController内置UIScrollView并调整其Frame?
Great question—this is a common pain point when working with UIPageViewController and splitting touch responsibility between different screen areas. Let’s break down your two core questions:
1. Is adjusting the frame of UIPageViewController's internal UIScrollView feasible?
Yes, this approach technically works—but with important caveats. When using the scroll transition style (UIPageViewControllerTransitionStyleScroll), the UIPageViewController does embed a UIScrollView to handle swiping between pages. Modifying this scroll view’s frame to only cover the upper half of the screen will restrict its touch detection to that area, allowing lower-half controls to receive touches as expected.
The key gotcha is that you’ll need to re-apply this frame adjustment every time the view layout updates (e.g., in viewDidLayoutSubviews), because the system may reset the scroll view’s frame during layout cycles. Here’s a quick example of how you might do this:
override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Locate the internal scroll view in the page view controller's hierarchy if let scrollView = pageViewController.view.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView { // Restrict scrollable area to the upper half of the screen scrollView.frame = CGRect( x: 0, y: 0, width: view.bounds.width, height: view.bounds.height / 2 ) } }
2. Is traversing the view hierarchy to find this scroll view "compliant"?
This is where things get nuanced:
- Technically, it’s allowed: Traversing the view hierarchy using public APIs like
subviewsdoesn’t violate Apple’s developer guidelines directly. - But it’s risky: The internal structure of
UIPageViewControlleris undocumented—Apple could redesign its view hierarchy (e.g., rename the scroll view class, rearrange subviews) in a future iOS update. This would break your code unexpectedly, leading to hard-to-debug bugs.
Apple strongly discourages relying on private implementation details, even if you’re using public APIs to access them. While this approach might not get your app rejected in review, it’s not a maintainable long-term solution.
Recommended Alternatives
To avoid depending on UIPageViewController’s internal structure, consider these more robust options:
- Custom gesture handling: Add a
UIPanGestureRecognizerto your parent view, check if the touch starts in the upper half, and manually trigger page transitions on theUIPageViewController. Don’t forget to disable the default scroll gestures on the page view controller to prevent conflicts. - Build a custom page controller: Use a
UIScrollVieworUICollectionView(with paging enabled) to implement your own page-switching logic. This gives you full control over the scrollable area and touch handling, with zero reliance on Apple’s private implementation details.
内容的提问来源于stack exchange,提问作者superbus

