使用 Storyboard 但需支援 iOS 5+,無法使用 Auto Layout。希望標題列高度固定,UIWebView 高度隨螢幕解析度自動填滿剩餘空間。
在建立 UIWebView 時(如 viewDidLoad 或 loadView),依螢幕框架計算 frame:
- (void)setupWebView {
// 取得應用程式可用區域(扣除狀態列)
CGRect webFrame = [[UIScreen mainScreen] applicationFrame]; // iOS 7 含狀態列高度
webFrame.origin.y -= 20.0; // 若需向上延伸覆蓋狀態列區域,視設計調整
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
webView.scalesPageToFit = YES;
webView.autoresizesSubviews = YES;
// 關鍵:設定自動調整遮罩,寬高隨父視圖變化
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
webView.backgroundColor = [UIColor clearColor];
[self.view addSubview:webView];
}
applicationFrame:回傳扣除狀態列後的螢幕矩形(iOS 7+ 含狀態列,需自行減 20pt)。autoresizingMask:Springs & Struts 機制核心,FlexibleWidth + FlexibleHeight 使視圖隨父視圖 bounds 縮放。scalesPageToFit = YES:網頁內容自動縮放至視圖寬度。- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration {
CGRect newFrame = [[UIScreen mainScreen] applicationFrame];
newFrame.origin.y -= 20.0;
self.webView.frame = newFrame;
}
UIWebView 已棄用(iOS 12+),新專案請改用 WKWebView,同樣適用 autoresizingMask。