如何在多任务时获取屏幕尺寸?

3
当用户在iPad Pro上拆分屏幕时,我希望能够获取视图的屏幕大小,以便根据要求动态设置视图。 使用[UIScreen mainScreen].bounds会给出整个屏幕的数据。

2
我认为在iOS中应该使用自动布局和尺寸类来处理这个问题。 - Eric Aya
谢谢您的快速回复,实际上我的应用程序具有动态视图,因此我没有使用自动布局。 - techloverr
我那时只需要屏幕尺寸。 - techloverr
2个回答

2

不要使用屏幕大小。一般情况下不要使用全局变量。

如果你是在编程方面做事情,而且很多人认为这与自动布局没有冲突,那么使用你的视图的 frame 来确定你的视图内容应该有多大。


1

请尝试使用[[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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接