我有一个视图控制器以编程方式设置,它具有一个子UIPageViewController.这显示了也以编程方式设置的各种其他视图控制器.这些视图控制器的视图将AutotoresizingMaskIntoConstraints设置为YES,但是页面视图控制器的视图使用约束将自身定位在顶视图控制器中.
问题是,当用户旋转设备时,页面视图控制器调整其框架大小,但其子视图控制器不会调整.通过didRotateFromInterfaceOrientation,它的框架仍然是从旧的方向.我已经验证了在子视图控制器上调用旋转方法,它们的框架不会改变.
我设置了这样的页面视图控制器:
self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil]; self.pageViewController.view.backgroundColor = [UIColor clearColor]; self.pageViewController.view.translatesAutoresizingMaskIntoConstraints = NO; self.pageViewController.dataSource = self; self.pageViewController.delegate = self; [self.pageViewController willMoveToParentViewController:self]; [self.view addSubview:self.pageViewController.view]; [self addChildViewController:self.pageViewController]; [self.pageViewController didMoveToParentViewController:self]; self.currentPageIndex = 0; self.currentPageController = [self pageForIndex:self.currentPageIndex]; self.currentPageController.delegate = self; [self.pageViewController setViewControllers:@[self.currentPageController] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:NULL];
我尝试调用setNeedsLayout,但它是一个笨拙的旋转动画,而我滑动的下一页也没有正确调整大小.
为什么页面浏览控制器不能调整其子视图控制器的大小,我该怎么做呢?
谢谢!
解决方法
首先,以自动布局,编程方式或故事板设置所有内容.然后,抓住父视图控制器中的方向更改,并强制UIPageViewController的视图重新布局.
这是我的工作代码(iOS 8.0及更高版本). childController1在故事板上设置了所有使用约束的布局,并用[self.storyboard instantiateViewControllerWithIdentifier:@“ChildControllerId”]实例化.
- (void)createPageController { ... pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil]; pageController.dataSource = self; [pageController setViewControllers:@[childController1] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil]; [self addChildViewController:pageController]; [self.view addSubview:pageController.view]; UIView *pageView = pageController.view; pageView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[pageView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(pageView)]]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[pageView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(pageView)]]; [pageController didMoveToParentViewController:self]; ... } - (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [pageController.view setNeedsLayout]; [super willTransitionToTraitCollection:newCollection withTransitionCoordinator:coordinator]; }
希望它有帮助.