本文介绍了iOS-检测viewDidLoad上的当前大小类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在iOS 8上使用自适应布局,我希望得到 viewDidLoad 上的大小类。关于这个的任何想法?

I'm working with adaptive Layout on iOS 8 and I want to get exactly what the size classes are on viewDidLoad. Any ideas about that?

推荐答案

从iOS 8开始 UIViewController 采用 UITraitEnvironment 协议。此协议声明名为 traitCollection 的属性,其类型为 UITraitCollection 。您只需使用 self.traitCollection

As of iOS 8 UIViewController adopts the UITraitEnvironment protocol. This protocol declares a property named traitCollection which is of type UITraitCollection. You can therefor access the traitCollection property simply by using self.traitCollection

traitCollection 属性> UITraitCollection 有两个要访问的属性,名为 horizo​​ntalSizeClass verticalSizeClass 访问这些属性会返回 NSInteger 。定义返回值的枚举在官方文档中声明如下 - (这有可能在将来添加!)

UITraitCollection has two properties that you want to access named horizontalSizeClass and verticalSizeClass Accessing these properties return an NSInteger. The enum that defines the returned values is declared in official documentation as follows- (this could potentially be added to in the future!)

typedef NS_ENUM (NSInteger, UIUserInterfaceSizeClass {
   UIUserInterfaceSizeClassUnspecified = 0,
   UIUserInterfaceSizeClassCompact     = 1,
   UIUserInterfaceSizeClassRegular     = 2,
};

所以你可以得到这个类并使用一个开关来确定你的代码方向。例如可以 -

So you could get the class and use say a switch to determine your code direction. An example could be -

NSInteger horizontalClass = self.traitCollection.horizontalSizeClass;
NSInteger verticalCass = self.traitCollection.verticalSizeClass;

switch (horizontalClass) {
    case UIUserInterfaceSizeClassCompact :
        // horizontal is compact class.. do stuff...
        break;
    case UIUserInterfaceSizeClassRegular :
        // horizontal is regular class.. do stuff...
        break;
    default :
        // horizontal is unknown..
        break;
}
// continue similarly for verticalClass etc.

这篇关于iOS-检测viewDidLoad上的当前大小类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 08:11