您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 範例:在網頁中點擊圖片放大檢視

編輯:iOS 開發綜合

在 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];
}

幾個可以改良的地方

  • 關閉時記得把 bgView 從父視圖移除並釋放,否則連點幾張圖會堆出一疊視圖。
  • 背景色可改成半透明黑並加上淡入動畫,視覺上會柔和很多。
  • 這套「自訂 URL scheme 攔截」的技巧,在 WKWebView 上要改用 navigationDelegate 的 decidePolicyForNavigationAction,或用 WKScriptMessageHandler 與網頁溝通,是更推薦的做法。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved