Autolayout is excellent for dynamically sizing your user-interface when developing for iOS or tvOS, but sometimes you need to know the specific device you're building for.
The following UIDevice
extension allows you to do exactly that. The values for each iPhone type indicate the screen size in inches. For instance, .iPhone55
refers to an iPhone 6 Plus / 6S Plus.
Place this code in a file such as UIDeviceExtension.swift
, or something similar.
import UIKit
extension UIDevice {
enum DeviceType {
case iPhone35
case iPhone40
case iPhone47
case iPhone55
case iPad
case TV
var isPhone: Bool {
return [ .iPhone35, .iPhone40, .iPhone47, .iPhone55 ].contains(self)
}
}
var deviceType: DeviceType? {
switch UIDevice.currentDevice().userInterfaceIdiom {
case .TV:
return .TV
case .Pad:
return .iPad
case .Phone:
let screenSize = UIScreen.mainScreen().bounds.size
let height = max(screenSize.width, screenSize.height)
switch height {
case 480:
return .iPhone35
case 568:
return .iPhone40
case 667:
return .iPhone47
case 736:
return .iPhone55
default:
return nil
}
case .Unspecified:
return nil
}
}
}
You can use this code as follows:
guard let type = UIDevice.currentDevice().deviceType
else {
// Unknown type
return
}
if type == .TV {
// Code specific to Apple TV
}
else if type == .iPhone47 {
// Code specific to iPhone 6/6S
}
else if type.isPhone {
// Code specific to other iPhones
}