Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Phát hiện thiết bị hiện tại với UIUserInterfaceIdiom trong Swift

Để phát hiện loại thiết bị (iPhone, iPad, TV, CarPlay) trong iOS/Swift, dùng UIDevice.current.userInterfaceIdiom – một enum chỉ ra "idiom" (kiểu giao diện) của thiết bị.

Các giá trị của UIUserInterfaceIdiom

enum UIUserInterfaceIdiom: Int {
    case unspecified      // Không xác định
    case phone            // iPhone và iPod touch
    case pad              // iPad
    case tv               // Apple TV (iOS 9+)
    case carPlay          // CarPlay (iOS 9+)
    case mac              // Mac Catalyst (iOS 13+)
    case vision           // Apple Vision Pro (iOS 17+)
}

Cách sử dụng

let idiom = UIDevice.current.userInterfaceIdiom
print("Device idiom: \(idiom)")

switch idiom {
case .phone:
    print("Đang chạy trên iPhone/iPod Touch")
    // UI cho phone: compact width, navigation stack
case .pad:
    print("Đang chạy trên iPad")
    // UI cho pad: regular width, split view, sidebar
case .tv:
    print("Đang chạy trên Apple TV")
    // Focus engine, remote control
case .carPlay:
    print("Đang chạy trên CarPlay")
    // Template-based UI, limited interaction
case .mac:
    print("Đang chạy trên Mac (Catalyst)")
case .vision:
    print("Đang chạy trên Vision Pro")
default:
    print("Thiết bị không xác định")
}

Kết quả chạy trên iPhone

Phát hiện thiết bị hiện tại với UIUserInterfaceIdiom trong Swift

Ứng dụng thực tế

  • Adaptive Layout: Xác định dùng Compact/Regular size class, hiển thị SplitViewController trên iPad vs NavigationController trên iPhone.
  • Feature gating: Bật/tắt tính năng tùy thiết bị (ví dụ: drag-drop chỉ iPad, CallKit chỉ iPhone).
  • Analytics: Ghi log loại thiết bị.

Lưu ý: userInterfaceIdiom phản ánh kiểu giao diện, không phải model cụ thể (iPhone 13 vs 14). Để biết model chính xác, dùng UIDevice.current.model (trả về "iPhone", "iPad") hoặc code máy (identifier) như bài 1003060619.