简体   繁体   English

iOS 检测用户是否在 iPad 上

[英]iOS detect if user is on an iPad

I have an app that runs on the iPhone and iPod Touch, it can run on the Retina iPad and everything but there needs to be one adjustment.我有一个可以在 iPhone 和 iPod Touch 上运行的应用程序,它可以在 Retina iPad 和所有东西上运行,但需要做一个调整。 I need to detect if the current device is an iPad.我需要检测当前设备是否是 iPad。 What code can I use to detect if the user is using an iPad in my UIViewController and then change something accordingly?我可以使用什么代码来检测用户是否在我的UIViewController使用 iPad,然后相应地更改某些内容?

There are quite a few ways to check if a device is an iPad.有很多方法可以检查设备是否是 iPad。 This is my favorite way to check whether the device is in fact an iPad:这是我最喜欢的检查设备是否真的是 iPad 的方法:

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

The way I use it我使用它的方式

#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. */
}   

Other Examples其他例子

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

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

For a Swift solution, see this answer: https://stackoverflow.com/a/27517536/2057171有关 Swift 解决方案,请参阅此答案: https : //stackoverflow.com/a/27517536/2057171

In Swift you can use the following equalities to determine the kind of device on Universal apps:Swift 中,您可以使用以下等式来确定通用应用程序上的设备类型

UIDevice.current.userInterfaceIdiom == .phone
// or
UIDevice.current.userInterfaceIdiom == .pad

Usage would then be something like:用法将类似于:

if UIDevice.current.userInterfaceIdiom == .pad {
    // Available Idioms - .pad, .phone, .tv, .carPlay, .unspecified
    // Implement your logic here
}

这是 iOS 3.2 中 UIDevice 的一部分,例如:

[UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad

You can also use this你也可以用这个

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

UI_USER_INTERFACE_IDIOM() only returns iPad if the app is for iPad or Universal. UI_USER_INTERFACE_IDIOM()仅在应用程序适用于 iPad 或通用时返回 iPad。 If its an iPhone app running on an iPad then it won't.如果它是在 iPad 上运行的 iPhone 应用程序,那么它就不会。 So you should instead check the model.所以你应该检查模型。

I found that some solution didn't work for me in the Simulator within Xcode.我发现某些解决方案在 Xcode 中的模拟器中对我不起作用。 Instead, this works:相反,这有效:

ObjC对象

NSString *deviceModel = (NSString*)[UIDevice currentDevice].model;

if ([[deviceModel substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"iPad"]) {
    DebugLog(@"iPad");
} else {
    DebugLog(@"iPhone or iPod Touch");
}

Swift迅速

if UIDevice.current.model.hasPrefix("iPad") {
    print("iPad")
} else {
    print("iPhone or iPod Touch")
}

Also in the 'Other Examples' in Xcode the device model comes back as 'iPad Simulator' so the above tweak should sort that out.同样在 Xcode 的“其他示例”中,设备模型作为“iPad 模拟器”返回,因此上面的调整应该可以解决这个问题。

Be Careful: If your app is targeting iPhone device only, iPad running with iphone compatible mode will return false for below statement:小心:如果您的应用程序仅针对 iPhone 设备,在 iphone 兼容模式下运行的 iPad 将返回 false 以下语句:

#define IPAD     UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad

The right way to detect physical iPad device is:检测物理 iPad 设备的正确方法是:

#define IS_IPAD_DEVICE      ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"])

Many Answers are good but I use like this in swift 4许多答案都很好,但我在 swift 4 中是这样使用的

  1. Create Constant创建常量

    struct App { static let isRunningOnIpad = UIDevice.current.userInterfaceIdiom == .pad ? true : false }
  2. Use like this像这样使用

    if App.isRunningOnIpad { return load(from: .main, identifier: identifier) } else { return load(from: .ipad, identifier: identifier) }

Edit: As Suggested Cœur simply create an extension on UIDevice编辑:根据建议,Cœur 只需在 UIDevice 上创建一个扩展

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

Many ways to do that in Swift :Swift 中有很多方法可以做到这一点:

We check the model below (we can only do a case sensitive search here):我们检查下面的模型(我们只能在这里进行区分大小写的搜索):

class func isUserUsingAnIpad() -> Bool {
    let deviceModel = UIDevice.currentDevice().model
    let result: Bool = NSString(string: deviceModel).containsString("iPad")
    return result
}

We check the model below (we can do a case sensitive/insensitive search here):我们检查下面的模型(我们可以在这里进行区分大小写/不区分大小写的搜索):

    class func isUserUsingAnIpad() -> Bool {
        let deviceModel = UIDevice.currentDevice().model
        let deviceModelNumberOfCharacters: Int = count(deviceModel)
        if deviceModel.rangeOfString("iPad",
                                     options: NSStringCompareOptions.LiteralSearch,
                                     range: Range<String.Index>(start: deviceModel.startIndex,
                                                                end: advance(deviceModel.startIndex, deviceModelNumberOfCharacters)),
                                     locale: nil) != nil {
            return true
        } else {
            return false
        }
   }

UIDevice.currentDevice().userInterfaceIdiom below only returns iPad if the app is for iPad or Universal. UIDevice.currentDevice().userInterfaceIdiom如果应用程序适用于 iPad 或 Universal,则下面的UIDevice.currentDevice().userInterfaceIdiom仅返回 iPad。 If it is an iPhone app being ran on an iPad then it won't.如果它是在 iPad 上运行的 iPhone 应用程序,则不会。 So you should instead check the model.所以你应该检查模型。 :

    class func isUserUsingAnIpad() -> Bool {
        if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
            return true
        } else {
            return false
        }
   }

This snippet below does not compile if the class does not inherit of an UIViewController , otherwise it works just fine.如果该类没有继承UIViewController ,则下面的这段代码不会编译,否则它工作得很好。 Regardless UI_USER_INTERFACE_IDIOM() only returns iPad if the app is for iPad or Universal.无论如何UI_USER_INTERFACE_IDIOM()仅在应用程序适用于 iPad 或 Universal 时才返回 iPad。 If it is an iPhone app being ran on an iPad then it won't.如果它是在 iPad 上运行的 iPhone 应用程序,则不会。 So you should instead check the model.所以你应该检查模型。 :

class func isUserUsingAnIpad() -> Bool {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad) {
        return true
    } else {
        return false
    }
}

* *

In swift 3.0在快速 3.0

* *

 if UIDevice.current.userInterfaceIdiom == .pad {
        //pad
    } else if UIDevice.current.userInterfaceIdiom == .phone {
        //phone
    } else if UIDevice.current.userInterfaceIdiom == .tv {
        //tv
    } else if UIDevice.current.userInterfaceIdiom == .carPlay {
        //CarDisplay
    } else {
        //unspecified
    }

In Swift 4.2 and Xcode 10Swift 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
}

If you want to detect specific device如果要检测特定设备

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
}

You can check the rangeOfString to see of the word iPad exists like this.您可以检查 rangeOfString 以查看 iPad 是否像这样存在。

NSString *deviceModel = (NSString*)[UIDevice currentDevice].model;

if ([deviceModel rangeOfString:@"iPad"].location != NSNotFound)  {
NSLog(@"I am an iPad");
} else {
NSLog(@"I am not an iPad");
}

Yet another Swifty way:另一种 Swifty 方式:

//MARK: -  Device Check
let iPad = UIUserInterfaceIdiom.Pad
let iPhone = UIUserInterfaceIdiom.Phone
@available(iOS 9.0, *) /* AppleTV check is iOS9+ */
let TV = UIUserInterfaceIdiom.TV

extension UIDevice {
    static var type: UIUserInterfaceIdiom 
        { return UIDevice.currentDevice().userInterfaceIdiom }
}

Usage:用法:

if UIDevice.type == iPhone {
    //it's an iPhone!
}

if UIDevice.type == iPad {
    //it's an iPad!
}

if UIDevice.type == TV {
    //it's an TV!
}

Why so complicated?为什么这么复杂? This is how I do it...我就是这样做的...

Swift 4:斯威夫特 4:

var iPad : Bool {
    return UIDevice.current.model.contains("iPad")
}

This way you can just say if iPad {}这样你就可以说if iPad {}

I don't think any of these answers meet my need, unless I am fundamentally misunderstanding something.我认为这些答案中的任何一个都不能满足我的需要,除非我从根本上误解了某些东西。

I have an app (originally an iPad app) that I want to run both on an iPad and on the Mac, under Catalyst.我有一个应用程序(最初是 iPad 应用程序),我想在 iPad 和 Mac 上的 Catalyst 下运行。 I'm using the plist option to scale the Mac interface to match the iPad, but would like to migrate to AppKit if that is reasonable.我正在使用 plist 选项来缩放 Mac 界面以匹配 iPad,但如果合理,我希望迁移到 AppKit。 When running on a Mac, I believe that all of the aforementioned approaches tell me that I'm on an iPad.在 Mac 上运行时,我相信上述所有方法都告诉我我在 iPad 上运行。 The Catalyst fake-out is pretty thorough. Catalyst 的伪造非常彻底。

For most concerns I indeed understand that the code should pretend it's on an iPad when thus running on a Mac.对于大多数问题,我确实理解代码在 Mac 上运行时应该假装它在 iPad 上。 One exception is that the rolling picker is not available on the Mac under Catalyst, but is on the iPad.一个例外是滚动选择器在 Catalyst 下的 Mac 上不可用,但在 iPad 上可用。 I want to figure out whether to create a UIPickerView or to do something different, at run time .我想弄清楚是在运行时创建 UIPickerView 还是做一些不同的事情。 Run-time selection is crucial because I want to use a single binary to run both on the iPad and Mac in the long term, while making the best use of the supported UI standards on each.运行时选择至关重要,因为我想长期使用单个二进制文件在 iPad 和 Mac 上运行,同时充分利用每个支持的 UI 标准。

The APIs give potentially misleading results to the casual pre-Catalyst reader.这些 API 会给临时的 Catalyst 读者提供潜在的误导结果。 For example, [UIDevice currentDevice].model returns @"iPad" when running under Catalyst on a Mac.例如, [UIDevice currentDevice].model在 Mac 上的 Catalyst 下运行时返回@"iPad" The user interface idiom APIs sustain the same illusion.用户界面习惯用法 API 维持相同的错觉。

I found that you really need to look deeper.我发现你真的需要更深入地研究。 I start with this information:我从以下信息开始:

NSString *const deviceModel = [UIDevice currentDevice].model;
NSProcessInfo *const processInfo = [[NSProcessInfo alloc] init];
const bool isIosAppOnMac = processInfo.iOSAppOnMac;  // Note: this will be "no" under Catalyst
const bool isCatalystApp = processInfo.macCatalystApp;

Then you can combine these queries with expressions like [deviceModel hasPrefix: @"iPad"] to sort out the kinds of subtleties I'm facing.然后,您可以将这些查询与[deviceModel hasPrefix: @"iPad"]类的表达式结合起来,以理清我面临的各种微妙之处。 For my case, I explicitly want to avoid making a UIPickerView if the indicated isCatalystApp is true , independent of "misleading" information about the interface idiom, or the illusions sustained by isIosAppOnMac and deviceModel .就我而言,如果指示的isCatalystApptrue ,则我明确希望避免创建 UIPickerView ,独立于有关界面习语的“误导性”信息,或由isIosAppOnMacdeviceModel维持的幻觉。

Now I'm curious what happens if I move the Mac app to run over on my iPad sidecar...现在我很好奇如果我移动 Mac 应用程序在我的 iPad 边车上运行会发生什么......

For the latest versions of iOS, simply add UITraitCollection :对于最新版本的 iOS,只需添加UITraitCollection

extension UITraitCollection {

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

and then within UIViewController just check:然后在UIViewController检查:

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

And now, with iOS 13... 而现在,有了iOS 13 ...

  if (UIDevice.current.userInterfaceIdiom == .pad) {
    // do stuff relevant to iPad
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM