为了账号安全,请及时绑定邮箱和手机立即绑定

在Swift中使用UI_USER_INTERFACE_IDIOM()检测当前设备

在Swift中使用UI_USER_INTERFACE_IDIOM()检测当前设备

慕慕森 2019-11-22 11:12:45
UI_USER_INTERFACE_IDIOM()在iPhone和iPad之间检测到的Swift 相当于什么?Use of unresolved identifier在Swift中编译时出现错误。
查看完整描述

3 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

使用Swift时,您可以使用enum UIUserInterfaceIdiom,定义为:


enum UIUserInterfaceIdiom : Int {

    case unspecified


    case phone // iPhone and iPod touch style UI

    case pad // iPad style UI

}

因此,您可以将其用作:


UIDevice.current.userInterfaceIdiom == .pad

UIDevice.current.userInterfaceIdiom == .phone

UIDevice.current.userInterfaceIdiom == .unspecified

或使用Switch语句:


    switch UIDevice.current.userInterfaceIdiom {

    case .phone:

        // It's an iPhone

    case .pad:

        // It's an iPad

    case .unspecified:

        // Uh, oh! What could it be?

    }

UI_USER_INTERFACE_IDIOM() 是一个Objective-C宏,定义为:


#define UI_USER_INTERFACE_IDIOM() \ ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? \ [[UIDevice currentDevice] userInterfaceIdiom] : \ UIUserInterfaceIdiomPhone)

另外,请注意,即使在使用Objective-C时,UI_USER_INTERFACE_IDIOM()也仅在定位iOS 3.2及更低版本时才需要该宏。部署到iOS 3.2及更高版本时,可以[UIDevice userInterfaceIdiom]直接使用。


查看完整回答
反对 回复 2019-11-22
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

Swift 2.0和iOS 9和Xcode 7.1


// 1. request an UITraitCollection instance

let deviceIdiom = UIScreen.mainScreen().traitCollection.userInterfaceIdiom


// 2. check the idiom

switch (deviceIdiom) {


case .Pad:

    print("iPad style UI")

case .Phone:

    print("iPhone and iPod touch style UI")

case .TV: 

    print("tvOS style UI")

default:

    print("Unspecified UI idiom")


}

Swift 3.0和Swift 4.0


// 1. request an UITraitCollection instance

let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom


// 2. check the idiom

switch (deviceIdiom) {


case .pad:

    print("iPad style UI")

case .phone:

    print("iPhone and iPod touch style UI")

case .tv: 

    print("tvOS style UI")

default:

    print("Unspecified UI idiom")

}

使用UITraitCollection。通过UITraitEnvironment协议的traitCollection属性公开了iOS trait环境。以下类别采用了此协议:


UIScreen

UIWindow

UIViewController

UIPresentationController

UIView


查看完整回答
反对 回复 2019-11-22
  • 3 回答
  • 0 关注
  • 1117 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信