什么是等价的UI_USER_INTERFACE_IDIOM()在Swift检测之间的iPhone和iPad?

我得到一个使用未解决的标识符错误时,在Swift编译。


当前回答

你可以在Swift 5上使用新的方式:

switch traitCollection.userInterfaceIdiom {
        
    case .unspecified:
        // do something
    case .phone:
        // do something
    case .pad:
        // do something
    case .tv:
        // do something
    case .carPlay:
        // do something
    case .mac:
        // do something
    @unknown default:
        // do something
}

其他回答

Swift 4.2 - 5.1扩展

 public extension UIDevice {

    class var isPhone: Bool {
        return UIDevice.current.userInterfaceIdiom == .phone
    }

    class var isPad: Bool {
        return UIDevice.current.userInterfaceIdiom == .pad
    }

    class var isTV: Bool {
        return UIDevice.current.userInterfaceIdiom == .tv
    }

    class var isCarPlay: Bool {
        return UIDevice.current.userInterfaceIdiom == .carPlay
    }
}

使用

if UIDevice.isPad {
   // Do something
}

Swift 2.0 & iOS 7+ / iOS 8+ / iOS 9+

public class Helper {
    public class var isIpad:Bool {
        if #available(iOS 8.0, *) {
            return UIScreen.mainScreen().traitCollection.userInterfaceIdiom == .Pad
        } else {
            return UIDevice.currentDevice().userInterfaceIdiom == .Pad
        }
    }
    public class var isIphone:Bool {
        if #available(iOS 8.0, *) {
            return UIScreen.mainScreen().traitCollection.userInterfaceIdiom == .Phone
        } else {
            return UIDevice.currentDevice().userInterfaceIdiom == .Phone
        }
    }
}

使用:

if Helper.isIpad {

}

OR

guard Helper.isIpad else {
    return
} 

由于@user3378170

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。 iOS trait环境是通过UITraitEnvironment协议的traitCollection属性公开的。以下类采用此协议:

UIScreen ui窗口 ui UIPresentationController UIView

如果你想检查当前设备是iPad还是iPhone,那么你可以使用这些代码行:

 if(UIDevice.currentDevice().userInterfaceIdiom == .Pad){

  }else if(UIDevice.currentDevice().userInterfaceIdiom == .Phone){

  }

斯威夫特3.0:

let userInterface = UIDevice.current.userInterfaceIdiom

if(userInterface == .pad){
    //iPads
}else if(userInterface == .phone){
    //iPhone
}else if(userInterface == .carPlay){
    //CarPlay
}else if(userInterface == .tv){
    //AppleTV
}