ios - 在 Swift 中使用 UI_USER_INTERFACE_IDIOM() 检测当前设备

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

在 Swift 中编译时出现 Use of unresolved identifier 错误。

最佳答案

使用 Swift 时,可以使用 enum UIUserInterfaceIdiom,定义为:

enum UIUserInterfaceIdiom : Int {
    case unspecified
    
    case phone // iPhone and iPod touch style UI
    case pad   // iPad style UI (also includes macOS Catalyst)
}

所以你可以把它用作:

UIDevice.current.userInterfaceIdiom == .pad
UIDevice.current.userInterfaceIdiom == .phone
UIDevice.current.userInterfaceIdiom == .unspecified

或者使用 Switch 语句:

    switch UIDevice.current.userInterfaceIdiom {
    case .phone:
        // It's an iPhone
    case .pad:
        // It's an iPad (or macOS Catalyst)

     @unknown default:
        // Uh, oh! What could it be?
    }

UI_USER_INTERFACE_IDIOM()是一个Objective-C宏,定义为:

#define UI_USER_INTERFACE_IDIOM() \ ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? \ [[UIDevice currentDevice] userInterfaceIdiom] : \ UIUserInterfaceIdiomPhone)

另外,请注意,即使在使用 Objective-C 时,UI_USER_INTERFACE_IDIOM() 宏也仅在面向 iOS 3.2 及更低版本时才需要。部署到 iOS 3.2 及以上版本时,可以直接使用 [UIDevice userInterfaceIdiom]

https://stackoverflow.com/questions/24059327/

相关文章:

objective-c - 在 Storyboard中,如何制作用于多个 Controller 的自

ios - 使用 NSURLSession 发送 POST 请求

ios - 查看保存的 NSUserDefaults 的简单方法?

ios - 如何以毫秒为单位准确记录方法的执行时间?

ios - 如果模态 ViewController 演示样式为 UIModalPresentatio

objective-c - 有没有办法从 UITableView 中删除分隔线?

ios - setNeedsLayout 与 setNeedsUpdateConstraints 和

objective-c - GCD 在主线程中执行任务

ios - 您可以将 UIGestureRecognizer 附加到多个 View 吗?

ios - 设置自定义 UITableViewCells 高度