首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 程式化獲取螢幕尺寸的標準方法:UIScreen mainScreen bounds

     編輯:程式設計綜合問答

標準代碼


// 獲取螢幕邊界(單位:points)
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenBounds.size.width;
CGFloat screenHeight = screenBounds.size.height;

NSLog(@"Screen: %.0f x %.0f", screenWidth, screenHeight);
// iPhone 4/4s: 320 x 480
// iPhone 5/5s/SE: 320 x 568
// iPhone 6/7/8: 375 x 667
// iPhone 6+/7+/8+: 414 x 736
// iPhone X/11 Pro: 375 x 812
// iPhone 11/12/13: 390 x 844 (邏輯點)

關鍵區別:Bounds vs Native Bounds

屬性含義單位
[UIScreen mainScreen].bounds邏輯座標系大小(開發用)Points
[UIScreen mainScreen].nativeBounds物理像素大小Pixels
[UIScreen mainScreen].scale縮放因子(Retina 2.0/3.0)倍數

nativeBounds = bounds * scale。佈局代碼永遠用 bounds (points)。

安全區域適配(iPhone X+ 刘海屏)


// 獲取安全區域內可用範圍
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIEdgeInsets safeInsets = window.safeAreaInsets; // iOS 11+
CGFloat safeTop = safeInsets.top;    // 狀態欄 + 刘海高度 (通常 44/47)
CGFloat safeBottom = safeInsets.bottom; // Home Indicator 高度 (通常 34)
CGFloat usableHeight = screenBounds.size.height - safeTop - safeBottom;

Swift 版本


let screenBounds = UIScreen.main.bounds
let width = screenBounds.width
let height = screenBounds.height

// 安全區域
let safeArea = UIApplication.shared.windows.first?.safeAreaInsets ?? .zero
let usableHeight = height - safeArea.top - safeArea.bottom

常見誤區

  • 用 self.view.frame 獲取螢幕尺寸:View 可能未佈局完成、有導航欄/標籤欄遮擋,不等於螢幕。
  • 硬編碼尺寸判斷機型:if (height == 812) // iPhone X 極易失效(新機型、分屏、旋轉)。改用 UIDevice 機型識別或自動佈局。

總結

**[[UIScreen mainScreen] bounds] 是獲取螢幕邏輯尺寸的唯一標準方法**。配合 safeAreaInsets 處理刘海屏,使用 Auto Layout / SnapKit 而非硬編碼座標,實現全機型適配。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved