iOS- Detect current size classes on viewDidLoad

笑着哭i 提交于 2019-11-28 17:28:43

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

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.

Some useful stuff for Swift 4:

UIViewController Extension to get the classes back as a Tuple.

extension UIViewController {
  func sizeClass() -> (UIUserInterfaceSizeClass, UIUserInterfaceSizeClass) {
      return (self.traitCollection.horizontalSizeClass, self.traitCollection.verticalSizeClass)
  }
}

Example Switch statement to consume the function:

    switch self.sizeClass() {
    case (UIUserInterfaceSizeClass.unspecified, UIUserInterfaceSizeClass.unspecified):
        print("Unknown")
    case (UIUserInterfaceSizeClass.unspecified, UIUserInterfaceSizeClass.compact):
        print("Unknown width, compact height")
    case (UIUserInterfaceSizeClass.unspecified, UIUserInterfaceSizeClass.regular):
        print("Unknown width, regular height")
    case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.unspecified):
        print("Compact width, unknown height")
    case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.unspecified):
        print("Regular width, unknown height")
    case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.compact):
        print("Regular width, compact height")
    case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.compact):
        print("Compact width, compact height")
    case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.regular):
        print("Regualr width, regular height")
    case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.regular):
        print("Compact width, regular height")
    }

Edit/Addition:

If you are trying to access the trait collection early in the UIViewController's lifecycle they might all be UIUserInterfaceSizeClass.unspecified.

This can be a pain if you happen to do constraints in code.

I recommend access the .traitCollection from the UIScreen shared object.

UIScreen.main.traitCollection

Or even more useful:

UIScreen.main.traitCollection.userInterfaceIdiom

This is nice for testing/debugging:

let sizeClasses = ["Unspecified", "Compact", "Regular"]
print("SizeClass w:\(sizeClasses[traitCollection.horizontalSizeClass.rawValue]) h:\(sizeClasses[traitCollection.verticalSizeClass.rawValue])")

You can also do it like that in Swift 5

enum DeviceTraitStatus {
    ///IPAD and others: Width: Regular, Height: Regular
    case wRhR
    ///Any IPHONE Portrait Width: Compact, Height: Regular
    case wChR
    ///IPHONE Plus/Max Landscape Width: Regular, Height: Compact
    case wRhC
    ///IPHONE landscape Width: Compact, Height: Compact
    case wChC

    static var current:DeviceTraitStatus{

        switch (UIScreen.main.traitCollection.horizontalSizeClass, UIScreen.main.traitCollection.verticalSizeClass){

        case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.regular):      
            return .wRhR
        case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.regular):
            return .wChR
        case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.compact):
            return .wRhC
        case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.compact):
            return .wChC
        default:
            return .wChR

        }

    }

}

The main advantatge is that can be used from not only a UIViewController class dependant and the static method can go into an i.e. Helper class. So you can do somewhere in your code:

let textSize:CGFloat = DeviceTraitStatus.current == .wRhR ? 18:14

So for Auto Layout you design your apps' UI per each different size class. The OS does all the work of figuring out the device being used and what size class should be used. However, if you there is a way to figure out what device is being used. I am not sure if you can decided what size class gets used as, again, this is handled dynamically by the OS.

Code for getting device being used:

NSString *device = [[UIDevice currentDevice]model ] ;
NSLog(@"%@",device);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!