有多种方法可以响应对分屏视图配置的更改。根据您想要的响应方式,您可能需要使用不同的方法。
Obj-C
- (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection {
if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
NSLog(@"split screen area now compact!");
} else if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassRegular) {
NSLog(@"split screen area now regular!");
}
}
斯威夫特:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if self.traitCollection.horizontalSizeClass == .compact {
print("split screen area now compact!")
}
}
这些方法在从 Compact 更改为 Regular 尺寸时调用,反之亦然。并非针对分屏视图句柄的每次调整。在其他情况下,则需要不同的代码。
与以编程方式处理旋转一样,您可能希望实现此方法,它将为您提供最终视图大小:
viewWillTransitionToSize:withTransitionCoordinator:
即使更改不足以跨越Regular-Compact 边界,也会调用此方法。检查传递给您的方法的size 参数,并查看示例,该示例显示您可以将在转换之前、期间和转换之后调用的代码放置在哪里。
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
// Code here will execute before the rotation begins.
// Equivalent to placing it in the deprecated method -[willRotateToInterfaceOrientation:duration:]
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Place code here to perform animations during the rotation.
// You can pass nil or leave this block empty if not necessary.
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Code here will execute after the rotation has finished.
// Equivalent to placing it in the deprecated method -[didRotateFromInterfaceOrientation:]
}];
}
更多阅读
我认为使用trait variations and size classes in your storyboards 也很有用,尽管这不是这个问题的具体答案。