在 UIWebView 裡顯示的網頁,點圖片時希望能全螢幕放大——這個效果不必修改網頁,靠 webView 的 delegate 就能攔下來。在 iPhone 6.1 上實測可運行。
當網頁中的連結被點擊,UIWebView 會先問 delegate「這個請求要不要載入」。我們在 shouldStartLoadWithRequest: 中檢查 URL 的開頭:如果是自訂的 pic: 前綴,就攔下來自己顯示大圖並回傳 NO;否則正常放行。網頁端只要把圖片的 href 寫成 pic:圖片名稱 即可。
實際效果:
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSString *picName = [[request URL] absoluteString];
NSLog(@"picName is %@", picName);
// hasPrefix 判斷是否以 pic: 開頭
if ([picName hasPrefix:@"pic:"]) {
[self showBigImage:[picName substringFromIndex:4]];
return NO; // 不走原本的載入流程
}
return YES;
}
- (void)showBigImage:(NSString *)imageName {
// 半透明灰色背景,讓背後內容無法操作
UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[bgView setBackgroundColor:[UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:0.7]];
[self.view addSubview:bgView];
[bgView release];
// 外框:圓角 + 淺色邊框
UIView *borderView = [[UIView alloc] initWithFrame:
CGRectMake(0, 0, BIG_IMG_WIDTH + 16, BIG_IMG_HEIGHT + 16)];
borderView.layer.cornerRadius = 8;
borderView.layer.masksToBounds = YES;
borderView.layer.borderWidth = 8;
borderView.layer.borderColor = [[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.7] CGColor];
[borderView setCenter:bgView.center];
[bgView addSubview:borderView];
[borderView release];
// 右上角關閉鈕
UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[closeBtn setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
[closeBtn addTarget:self action:@selector(removeBigImage:)
forControlEvents:UIControlEventTouchUpInside];
[closeBtn setFrame:CGRectMake(borderView.frame.origin.x + borderView.frame.size.width - 20,
borderView.frame.origin.y - 6, 26, 27)];
[bgView addSubview:closeBtn];
// 中間的圖
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, BIG_IMG_WIDTH, BIG_IMG_HEIGHT)];
[imgView setImage:[UIImage imageNamed:imageName]];
[borderView addSubview:imgView];
[imgView release];
}
navigationDelegate 的 decidePolicyForNavigationAction,或用 WKScriptMessageHandler 與網頁溝通,是更推薦的做法。