做多機型適配時,常常需要知道使用者手上是哪一台裝置,再依寬高、解析度決定控制項與圖片尺寸。最簡便的判斷依據是主螢幕的 bounds。
CGRect rect = [[UIScreen mainScreen] bounds];
bounds 回傳的是 CGRect 結構,其中 size 是 CGSize,包含 width 與 height 兩個成員。把這組數字對照各機型的解析度,就能反推機型。
UIDevice+IPhoneModel.h:
typedef NS_ENUM(char, iPhoneModel) { // 0~3
iPhone4, // 320 * 480
iPhone5, // 320 * 568
iPhone6, // 375 * 667
iPhone6Plus, // 414 * 736
UnKnown
};
@interface UIDevice (IPhoneModel)
/**
return current running iPhone model
@return iPhone model
*/
+ (iPhoneModel)iPhonesModel;
@end
UIDevice+IPhoneModel.m:
#import "UIDevice+IPhoneModel.h"
@implementation UIDevice (IPhoneModel)
+ (iPhoneModel)iPhonesModel {
// 注意:bounds 取得的是 point 而非 pixel
CGRect rect = [[UIScreen mainScreen] bounds];
CGFloat width = rect.size.width;
CGFloat height = rect.size.height;
// 取得目前的方向
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (UIInterfaceOrientationUnknown == orientation) {
return UnKnown;
}
// portrait: width * height
// iPhone4:320*480 iPhone5:320*568 iPhone6:375*667 iPhone6Plus:414*736
if (UIInterfaceOrientationPortrait == orientation) {
if (width == 320.0f) {
if (height == 480.0f) {
return iPhone4;
} else {
return iPhone5;
}
} else if (width == 375.0f) {
return iPhone6;
} else if (width == 414.0f) {
return iPhone6Plus;
}
} else if (UIInterfaceOrientationLandscapeLeft == orientation
|| UIInterfaceOrientationLandscapeRight == orientation) {
// landscape 時寬高互換
if (height == 320.0) {
if (width == 480.0f) {
return iPhone4;
} else {
return iPhone5;
}
} else if (height == 375.0f) {
return iPhone6;
} else if (height == 414.0f) {
return iPhone6Plus;
}
}
return UnKnown;
}
@end
這段程式刻意區分了直向與橫向:橫向時寬高會對調,所以判斷依據要換成 height。若不處理方向,同一台裝置旋轉螢幕後就可能被判成未知機型。
最後提醒一個重點:[[UIScreen mainScreen] bounds] 回傳的是 point,不是 pixel。若要拿真正的硬體解析度,應該用 scale 相乘,或直接讀取 nativeBounds。另外這種以尺寸反推機型的方式在 Apple 推出新機型後勢必需要更新表格,若你的目的只是「依可用空間配置版面」,用 Auto Layout 或尺寸分類(size class)通常比硬判機型更耐用。