我有一款应用可以在iPhone和iPod Touch上运行,也可以在Retina iPad和其他设备上运行,但需要做一些调整。我需要检测当前设备是否是iPad。我可以用什么代码来检测用户是否在我的UIViewController中使用iPad,然后相应地改变一些东西?


当前回答

很多答案都很好,但我在swift 4中使用这样的答案

创建常量 struct App { 静态let isRunningOnIpad = UIDevice.current.userInterfaceIdiom == .pad ?True: false } 像这样使用 if App.isRunningOnIpad { 返回加载(from: .main, identifier: identifier) }其他{ 返回加载(from: .ipad, identifier: identifier) }

编辑:建议ceure简单地在UIDevice上创建一个扩展

extension UIDevice {
    static let isRunningOnIpad = UIDevice.current.userInterfaceIdiom == .pad ? true : false
}

其他回答

if(UI_USER_INTERFACE_IDIOM () == UIUserInterfaceIdiom.pad)
 {
            print("This is iPad")
 }else if (UI_USER_INTERFACE_IDIOM () == UIUserInterfaceIdiom.phone)
 {
            print("This is iPhone");
  }

在Swift 4.2和Xcode 10中

if UIDevice().userInterfaceIdiom == .phone {
    //This is iPhone
} else if UIDevice().userInterfaceIdiom == .pad { 
    //This is iPad
} else if UIDevice().userInterfaceIdiom == .tv {
    //This is Apple TV
}

如果你想检测特定的设备

let screenHeight = UIScreen.main.bounds.size.height
if UIDevice().userInterfaceIdiom == .phone {
    if (screenHeight >= 667) {
        print("iPhone 6 and later")
    } else if (screenHeight == 568) {
        print("SE, 5C, 5S")
    } else if(screenHeight<=480){
        print("4S")
    }
} else if UIDevice().userInterfaceIdiom == .pad { 
    //This is iPad
}

对于最新版本的iOS,只需添加UITraitCollection:

extension UITraitCollection {

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

然后在UIViewController中检查:

if traitCollection.isIpad { ... }

你也可以用这个

#define IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
...
if (IPAD) {
   // iPad
} else {
   // iPhone / iPod Touch
}

有很多方法可以检查设备是否为iPad。这是我最喜欢的检查设备是否真的是iPad的方法:

if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
    return YES; /* Device is iPad */
}

我使用它的方式

#define IDIOM    UI_USER_INTERFACE_IDIOM()
#define IPAD     UIUserInterfaceIdiomPad

if ( IDIOM == IPAD ) {
    /* do something specifically for iPad. */
} else {
    /* do something specifically for iPhone or iPod touch. */
}   

其他的例子

if ( [(NSString*)[UIDevice currentDevice].model hasPrefix:@"iPad"] ) {
    return YES; /* Device is iPad */
}

#define IPAD     (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
if ( IPAD ) 
     return YES;

有关Swift解决方案,请参阅以下答案:https://stackoverflow.com/a/27517536/2057171