当用户在iPad Pro上拆分屏幕时,我希望能够获取视图的屏幕大小,以便根据要求动态设置视图。 使用[UIScreen mainScreen].bounds会给出整个屏幕的数据。
不要使用屏幕大小。一般情况下不要使用全局变量。
如果你是在编程方面做事情,而且很多人认为这与自动布局没有冲突,那么使用你的视图的 frame
来确定你的视图内容应该有多大。
请尝试使用[[UIApplication sharedApplication] keyWindow].bounds
。
请注意,在应用程序进入/返回后台状态或进行窗口的自定义操作时,可能会得到奇怪的结果。
完整故事: 我不得不实现一些类似的东西,我的自定义大小类,以确定我的支持多任务的通用应用程序处于紧凑、常规或完整状态(完整状态定义为横向iPad非分屏) - 像这样解决它:
typedef NS_ENUM (NSInteger, OBDTraitStyle) {
OBDTraitStyleCompact,
OBDTraitStyleMedium,
OBDTraitStyleFull
};
static NSNumber *_previousGlobalTraitStyleNumber = nil;
@implementation UITraitCollection (OBD)
- (OBDTraitStyle)obd_traitStyle
{
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground)
{
if (_previousGlobalTraitStyleNumber != nil)
{
NSLog(@"App in background - returning previous trait style: %ld", (long)[_previousGlobalTraitStyleNumber integerValue]);
return [_previousGlobalTraitStyleNumber integerValue];
}
else
{
NSLog(@"App in background - cannot return previous trait style, as it doesn't exist");
}
}
OBDTraitStyle traitStyle = 0;
if (self.horizontalSizeClass == UIUserInterfaceSizeClassCompact)
{
traitStyle = OBDTraitStyleCompact;
}
else
{
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
if (window.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact)
{
traitStyle = OBDTraitStyleCompact;
}
else
{
CGSize viewSize = window.bounds.size;
BOOL horizontalExpanded = (viewSize.width > 768);
if (horizontalExpanded == NO)
{
traitStyle = OBDTraitStyleMedium;
}
else
{
traitStyle = OBDTraitStyleFull;
}
}
}
_previousGlobalTraitStyleNumber = @(traitStyle);
return traitStyle;
}
@end