检查设备是否为iPad。

29

这段代码有什么问题?我想要检查用户当前使用的设备是否是iPad,但它一直给我错误。

if (UIUserInterfaceIdiom == UIUserInterfaceIdiomPad)
{
    //do stuff
}

你可能想要给它打上不止 iPad 的标签。 - epascarello
也许你调用它的时间太晚了?你是手动加载XIB吗?我记得我曾经这样做并成功了。但我想还有更好的解决方案。 - Daniel Monteiro
7个回答

44

你可以使用

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

7
请注意,UIUserInterfaceIdiomPhone值并不一定意味着你在iPhone设备上 - 而是界面风格与iPhone匹配。你可能在iPad上运行仅支持iPhone的应用程序并处于1x/2x模式。 - magma
2
实际上这是UI_USER_INTERFACE_IDIOM()。 - rmaddy
这是一个有趣的观点,Magma,谢谢你让我注意到它。我不知道那是事实。 - Makleesh

43

在 Swift 中,您可以使用:

if UIDevice.current.userInterfaceIdiom == .pad {
    //do stuff
}

7

您需要检查设备是否为 iPhone/iPad。

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
//do ur  ipad logic
}else
{
//do ur  iphone logic
}

5

/* UI_USER_INTERFACE_IDIOM()函数适用于部署到iOS 3.2以下版本时使用。如果您将部署的iPhone/iOS的最早版本为3.2或更高版本,则可以直接使用-[UIDevice userInterfaceIdiom]。 */

除非您支持超级老的iOS,否则最好使用UIDevice.current.userInterfaceIdiom

可能的情况如下:

public enum UIUserInterfaceIdiom : Int {
    case unspecified

    @available(iOS 3.2, *)
    case phone // iPhone and iPod touch style UI

    @available(iOS 3.2, *)
    case pad // iPad style UI

    @available(iOS 9.0, *)
    case tv // Apple TV style UI

    @available(iOS 9.0, *)
    case carPlay // CarPlay style UI
}

4
如果您正在使用Swift,请使用以下内容:
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad)
    {
      // device is ipad
    }
    else
    {
        //  device is iPhone
    }

0

我的应用程序在iPad上作为仅iPhone应用程序运行,但我仍然需要检测设备是否为iPad以隐藏与Apple HealthKit相关的某些功能,因为它不可用于iPad。我使用了这种方法。

extension UIDevice {
    var isPad: Bool {
        get {
            return UIDevice.deviceInfo.lowercased().containsWord("ipados")
        }
    }
}

0

OBJC:

if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad){
        //do awesome objc stuff!;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接