Can I detect if screen is regular or compact from code on iOS 8?

本小妞迷上赌 提交于 2019-12-21 03:12:05

问题


iOS 8 introduce new screen types that are usable in Storyboards and in Xibs, can I detect these types in code? If yes, how?

Here you can find more about it https://developer.apple.com/library/content/releasenotes/General/WhatsNewIniOS/Articles/iOS8.html


回答1:


Yes you can, UIViewControllers now have a traitCollection property which has information from the device idiom, to the current size classes and more ... Furthermore you can implement the method func traitCollectionDidChange(previousTraitCollection: UITraitCollection) to get notifications when the size class (or any trait) has changed (as when the user rotates the device on an iphone). The properties of UITraitCollection that you are looking for are horizontalSizeClass and verticalSizeClass ..Here is a reference

Hope that helps




回答2:


You can also detect kind of device and its orientation using below extension:

extension UITraitCollection {

    var isIpad: Bool {
        return horizontalSizeClass == .regular && verticalSizeClass == .regular
    }

    var isIphoneLandscape: Bool {
        return verticalSizeClass == .compact
    }

    var isIphonePortrait: Bool {
        return horizontalSizeClass == .compact && verticalSizeClass == .regular
    }

    var isIphone: Bool {
        return isIphoneLandscape || isIphonePortrait
    }
}



回答3:


From the page you linked (emphasis added):

The UITraitCollection class is used to describe a collection of traits assigned to an object. Traits specify the size class, display scale, and idiom for a particular object. Classes that support the UITraitEnvironment protocol (such as UIViewController and UIView) own a trait collection. You can retrieve an object’s trait collection and perform actions when those traits change.

As noted in the references linked from there, you can implement the traitCollectionDidChange method in your view or view controller to find out when the size class changes.



来源:https://stackoverflow.com/questions/25794954/can-i-detect-if-screen-is-regular-or-compact-from-code-on-ios-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!