在 iOS 應用中嵌入網頁內容是常見需求。雖然現代開發推薦使用 WKWebView,但理解 UIWebView 的基本用法仍有助於維護舊專案或快速原型驗證。
@property (strong, nonatomic) UIWebView *webView;
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化 WebView,框架填滿螢幕(以 iPhone 4/4S 320x480 為例)
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[self.view addSubview:self.webView];
// 建立請求並載入
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
[self.webView loadRequest:request];
}
self.view.bounds 自適應螢幕尺寸。UIWebViewDelegate 可監聽載入進度、錯誤處理、導航攔截等。Info.plist 配置 NSAppTransportSecurity 允許特定域名或全域放開。self.webView.delegate = nil 並 [self.webView stopLoading],避免野指針崩潰。掌握這段基礎代碼,即可在幾分鐘內為 App 加入網頁瀏覽能力。