我有一款应用可以在iPhone和iPod Touch上运行,也可以在Retina iPad和其他设备上运行,但需要做一些调整。我需要检测当前设备是否是iPad。我可以用什么代码来检测用户是否在我的UIViewController中使用iPad,然后相应地改变一些东西?
当前回答
在Swift中,您可以使用以下等式来确定通用应用程序上的设备类型:
UIDevice.current.userInterfaceIdiom == .phone
// or
UIDevice.current.userInterfaceIdiom == .pad
用法就像这样:
if UIDevice.current.userInterfaceIdiom == .pad {
// Available Idioms - .pad, .phone, .tv, .carPlay, .unspecified
// Implement your logic here
}
其他回答
有很多方法可以检查设备是否为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
斯威夫特的另一种方式:
//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 }
}
用法:
if UIDevice.type == iPhone {
//it's an iPhone!
}
if UIDevice.type == iPad {
//it's an iPad!
}
if UIDevice.type == TV {
//it's an TV!
}
我发现在Xcode中的模拟器中,有些解决方案并不适合我。相反,这是可行的:
ObjC
NSString *deviceModel = (NSString*)[UIDevice currentDevice].model;
if ([[deviceModel substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"iPad"]) {
DebugLog(@"iPad");
} else {
DebugLog(@"iPhone or iPod Touch");
}
斯威夫特
if UIDevice.current.model.hasPrefix("iPad") {
print("iPad")
} else {
print("iPhone or iPod Touch")
}
同样在Xcode中的“其他示例”中,设备模型返回为“iPad模拟器”,因此上述调整应该将其整理出来。
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中使用这样的答案
创建常量 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
}
推荐文章
- 为什么Swift的编译时间这么慢?
- iPhone上UIView和UILabels的渐变
- 如何测试等价的Swift枚举与相关的值
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- 在Swift中转换Float为Int
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 我如何在Swift中声明一个弱引用数组?
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?