【问题标题】:How do I position a subview in UIPageViewController using Auto Layout?如何使用自动布局在 UIPageViewController 中定位子视图?
【发布时间】:2014-03-16 02:24:32
【问题描述】:

我有一个UIPageViewController 子类,我想在它的viewDidLoad 中添加一个UILabel 到它的self.view。如果我使用框架设置它的位置,这工作正常,但如果我尝试使用自动布局定位它,我得到:

* -[_UIPageViewControllerContentView layoutSublayersOfLayer:] 中的断言失败,/SourceCache/UIKit_Sim/UIKit-2935.58/UIView.m:8742

我应该如何定位此 UILabel 以显示在 UIPageViewController 中?

【问题讨论】:

  • 假设断言是因为约束冲突,你还记得 translatesAutoresizingMaskIntoConstraints = NO 吗?
  • 是的,我确实记得。
  • 您是否也收到消息“执行 -layoutSubviews 后仍需要自动布局”?

标签: ios objective-c uiview autolayout uipageviewcontroller


【解决方案1】:

您还可以继承 UIPageViewController 并实现此解决方法:

#import <objc/runtime.h>

@interface MyPageViewController : UIPageViewController
@end

@implementation MyPageViewController
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self applyLayoutSubviewsWorkaroundIfNeeded];
}

- (void)applyLayoutSubviewsWorkaroundIfNeeded {
    // UIPageViewController does not support AutoLayout in iOS7, we get the following runtime error
    // "_UIPageViewControllerContentView’s implementation of -layoutSubviews needs to call super…"
    // This workaround calls the missing layoutSubviews method of UIView.
    if ([self iOSVersionIsLowerThan8]) {
        IMP uiviewLayoutSubviewsImplementation = class_getMethodImplementation([self.view class], @selector(layoutSubviews));
        typedef void (*FunctionFromImplementation)(id, SEL);
        FunctionFromImplementation uiviewLayoutSubviewsFunction = (FunctionFromImplementation)uiviewLayoutSubviewsImplementation;
        uiviewLayoutSubviewsFunction(self.view, @selector(layoutSubviews));
    }
}

- (BOOL)iOSVersionIsLowerThan8 {
    // This is just one way of checking if we are on iOS7. 
    // You can use whatever method suits you best
    return ![self respondsToSelector(popoverPresentationController)];
}
@end

【讨论】:

    【解决方案2】:

    这似乎正在发生,因为UIPageViewController 的视图(实际上是_UIPageViewControllerContentView)没有按预期处理子视图和自动布局(至少在 iOS 7 中;它在 iOS 8 中对我来说很好用)。

    你可以通过不使用自动布局来解决这个问题,但我想使用自动布局,所以我最终重做了我的视图控制器以避免将子视图添加到 UIPageViewController

    我没有将UIPageViewController 子类化,而是创建了一个容器视图控制器(UIViewController 的子类),并将UIPageViewController 作为子视图控制器。我最初在UIPageViewController 中拥有的自定义子视图随后被添加到容器的view 中。我还将容器作为UIPageViewController 的数据源和委托。

    有一个相关的线程,人们遇到了同样的断言失败,但UITableViewCell"Auto Layout still required after executing -layoutSubviews" with UITableViewCell subclass。那里的大多数建议都不起作用或不适用于 UIPageViewController,但它帮助我弄清楚了为什么添加带有自动布局的子视图可能会导致问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-13
      • 2014-02-25
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多