iOS UIWebView基礎知識

1.只有使用loadRequest:加載網頁,才能對之後的鏈接操作做goBack,goForward操作,即canGoBack,canGoForward纔有可能返回YES.

   使用loadHTMLString,loadData都不可以.

  並且在load之後通過stringByEvaluatingJavaScriptFromString對網頁增加的內容,在

  NSString* outerHTML = [iWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];//document.documentElement.innerHTML

  中都不會出現。

   可以使用loadRequestl加載本地文件,但還不能解決其中的網絡圖片問題:

   NSURLRequest* request=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:@“/Users/../1.html”]]; 
    [iWebView loadRequest:request];

   使用loadRequest,NSURLRequest 的代理獲得進度?

2.把要請求的地址直接交於UIWebView loadRequest,它在請求時,也會把這個地址回調到shouldStartLoadWithRequest代理方法中,詢問是否由瀏覽器自己請求.

   把內容直接設置給UIWebView,之後在請求內容中的圖片時不會調用shouldStartLoadWithRequest。

   另外內容中有些需要加Referer頭的圖片,不能過通過UIWebView設置這個頭。即 shouldStartLoadWithRequest中,request即使是NSMutableURLRequest類型,設置request的頭,請求後這些頭不會被帶。

3.goBack也會請求頁面,也會回調代理方法.

4. NSURLErrorDomain error -999.

This error may occur if an another request is made before the previous request of WebView is completed...

I worked around this by ignoring this error and letting the webview continue to load.

5.雙擊一個圖片鏈接不會調用到shouldStartLoadWithRequest

  判斷點擊到的是否是圖片,可設置特殊的url,或判斷當前點擊的tag,使用window.pageYOffset,window.pageXOffset,window.outerWidth,document.elementFromPoint等。

  例如 NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];,

                           js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).getAttribute('_src')", pt.x, pt.y]; 
   獲取自定義屬性的值時,用getAttribute。

7.設置背景色後,如下:iWebView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];

   當內容很長時,會佔用很大內存,這說明它會根據ContentSize平鋪,而不是Bounds;

   使用iWebView.backgroundColor=[UIColor blackColor];則不會佔用這麼大的內存。

8.webView_.opaque = NO;//設置webView最上面的內容的背景透明

   webView_.backgroundColor=[UIColor clearColor];//設置其中的scrollView透明

   使用圖片背景的方案是:在iWebView的下面同級加一層UIImageView, iWebView.backgroundColor=[UIColor clearColor];,當內容拖動到頭或尾時,會透出iWebView下面的背景。

   如果要讓內容的背景也透明,再設置不透明屬性爲NO:webView.opaque = NO;

   利用這些屬性可以實現在頂部或底部拖動時,展現刷新提示效果;

8.在頂部和底部時,禁用拖動回彈: 
    for (id subview in iWebView.subviews) 
    { 
        if ([[subview class] isSubclassOfClass: [UIScrollView class]]) 
        { 
            ((UIScrollView *)subview).bounces = NO; 
        } 
    }

禁止UIWebView的bounces 
http://www.flyblog.info/catprogramming/303.html

    底部灰色陰影其實是個imageview,hidden就行了,不影響任何正常操作: 
    for(UIView *v in [[[iWebView subviews] objectAtIndex:0] subviews]) 
    { 
        if([v isKindOfClass:[UIImageView class]]) 
        { 
            v.hidden = YES; 
        } 
    }

讓網頁自適應屏幕

webview.scalesPageToFit = YES;

在網頁中寫下面的js代碼,也可以實現bounces = NO的功能

document.onload = function(){
	 document.ontouchmove = function(e){ e.preventDefault(); }
}

9.由此服務端日誌記錄可知,iphone端safiri及UIWebView的圖片緩存是沒有的。每次訪問都需要從服務端重新下載圖片

http://tangqiaoboy.blog.163.com/blog/static/11611425820118672051584/

10.UIWebView的stringByEvaluatingJavaScriptFromString只能在主線程裏面被調用,如果恰好這個js執行時間比較長,就會造成程序卡死。

     跟 Mac OS X 比較起來,iPhone 上 UIWebView 的公開 API 實在少上許多.

http://spring-studio.net/?p=265

11.UIWebView之獲取所點位置圖片URL

http://www.cocoachina.com/newbie/basic/2011/1031/3439.html

12.顯示本地圖片

     NSString*  logoPath=[FileUtil getDocumentsFullPath:@"logol.png"];

或 NSString*  logoPath=[[NSBundle mainBundle] pathForResource:@"logol" ofType:@"png"]; 
     NSString* local_image_path=[NSString stringWithFormat:@"file://%@",pathForResource]; 
    NSString* script=[NSString stringWithFormat:@"changeImgSrc(\"%@\");",local_image_path]; 
    [iWebView stringByEvaluatingJavaScriptFromString:script];

    例如:baseUrl設置爲:file:///Users/gzty1/Library/Application Support/iPhone Simulator/4.2/Applications/85B80321-2BBC-4FFA-9D3D-2DD1B/myapp.app/

              image.src 設置爲file:///Users/gzty1/Library/Application Support/iPhone Simulator/4.2/Applications/85B80321-2BBC-4FFA-9D3D-2DD1B/myapp.app/logo.png

     注意:file後面是冒號加3個斜槓。

    //顯示安裝包中的圖片,baseURL使用[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]

    [webView_ loadHTMLString:htmlContent baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

13. 禁用長按UIWebView時放大鏡及選擇功能:

//通過js調用

- (void)webViewDidFinishLoad:(UIWebView*)webView

{

// Disable user selection

[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];

// Disable callout,禁止長按鏈接彈出菜單,默認帶有打開,拷貝,取消3個菜單項。

[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];

//修改整個頁面的字體大小

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '150%';"];

//修改點擊鏈接時的高亮背景色

[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTapHighlightColor='#FF0000';"];

}

//嵌入在頁面中

//修改點擊鏈接時的高亮背景色

<a href=http://yourlink.com/ style = "-webkit-tap-highlight-color:rgba(0,0,0,0);">

webkit webApp 開發技術要點總結 
http://www.cnblogs.com/pifoo/archive/2011/05/28/webkit-webapp.ht

14.禁用UIWebView中雙擊和手勢縮放頁面,但測試結果是縮小了一半,確實不影響雙擊了,但不縮小時仍然響應雙擊上下滾動。

http://blog.163.com/alex_kame/blog/static/14546748201171263254740/

http://learnthemobileweb.com/2009/07/mobile-meta-tags/

15.用UIWebView顯示gif

        UIImage* tempImage=[UIImage imageWithData:data]; 
        CGRect rect = CGRectZero; 
        rect.size = tempImage.size; 
        iWebView = [[UIWebView alloc] initWithFrame:rect]; 
        [self addSubview:iWebView]; 
        [iWebView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil]; 
        iWebView.userInteractionEnabled=NO; 
        iWebView.opaque = NO; 
        iWebView.backgroundColor=[UIColor clearColor];

16. UIWebView處理authentication方法 
      參考 http://www.cocoachina.com/newbie/basic/2011/1123/3583.html

17.elementFromPoint() under iOS 5 
http://www.icab.de/blog/2011/10/17/elementfrompoint-under-ios-5/

NSString* js = [NSString stringWithFormat:@"elementFromViewportPoint(%f, %f).tagName", pt.x, pt.y];

//private

function viewportCoordinateToDocumentCoordinate(x,y) 

  var coord = new Object(); 
  coord.x = x + window.pageXOffset; 
  coord.y = y + window.pageYOffset; 
  return coord; 
}

//private

function elementFromPointIsUsingViewPortCoordinates() 

  if (window.pageYOffset > 0) 
  {    
// page scrolled down 
    return (window.document.elementFromPoint(0, window.pageYOffset + window.innerHeight -1) == null); 
  } 
  else if (window.pageXOffset > 0) 
  {   
// page scrolled to the right 
    return (window.document.elementFromPoint(window.pageXOffset + window.innerWidth -1, 0) == null); 
  } 
  return false; // no scrolling, don't care 
}

//public

function elementFromViewportPoint(x,y) 

  if (elementFromPointIsUsingViewPortCoordinates()) 
  { 
    return window.document.elementFromPoint(x,y); 
  } 
  else 
  { 
    var coord = viewportCoordinateToDocumentCoordinate(x,y); 
    return window.document.elementFromPoint(coord.x,coord.y); 
  } 
}

內容高度 : int contentHeight=[[webView_ stringByEvaluatingJavaScriptFromString:@"document.body.clientHeight"] intValue];

18.滾動到頂部

    [webView_ stringByEvaluatingJavaScriptFromString:@"window.scrollTo(0,0);"];

19.在UIGestureRecognizer的響應函數中調用打開一個有輸入框的頁面,UIGestureRecognizer的響應中後續會讓webview再次獲得焦點,從而使鍵盤隱藏。

     這樣把事件放到shouldStartLoadWithRequest中來曲線解決問題。

20. webapp是css+html來描述的,沒辦法簡單的用name@2x 解決問題,繼續求教中

iphone4圖片問題

http://aralbalkan.com/3331

在head中添加 <meta name="viewport" content="width=device-width, initial-scale=0.5, minimum-scale=0.5, maximum-scale=yes" />

                       <meta  align="center" name="viewport" content="width=480; initial-scale=0.5; maximum-scale=0.5;  user-scalable=no;"/>

也可以控制頁面的縮放,但並不統一。

爲視網膜顯示屏優化網頁上的圖片 
(via:http://xuui.net/ui-design/retinal-display-to-optimize-the-image-the-on-the-the-page.html).

在網頁中,pixel 與 point 比值稱爲 device-pixel-ratio,普通設備都是1,iPhone 4是2,有些Android機型是1.5。

Detecting taps and events on UIWebView – The right way

http://mithin.in/2009/08/26/detecting-taps-and-events-on-uiwebview-the-right-way

21.對UIWebView中的數據的網絡請求,js操作,一定要放到webViewDidFinishLoad調用之後,否則很可能出現找不到標籤的異常問題。!!

     html模板中,把要替換的內容放在div中,不要放在p中,否則不保證樣式正常顯示。

22.在頂部向下拖動一段距離的事件

    UIScrollView* scrollView = [webView_.subviews objectAtIndex:0]; 
    if (scrollView && [scrollView isKindOfClass:[UIScrollView class]]) 
    { 
        scrollView.delegate = self; 
    }

     - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate 
   { 
    CGPoint offset = scrollView.contentOffset; 
    NSLog(@"%@",NSStringFromCGPoint(offset)); 
    if(offset.y<=-60.0) 
    { 
        [super onNavigationBackPressed]; 
    } 
   }

23.

    webView_=[[UIWebView alloc] initWithFrame:webRect]; 
    webView_.delegate=self; 
    webView_.dataDetectorTypes = UIDataDetectorTypeNone; 
    webView_.opaque = NO; //背景透明 
    webView_.backgroundColor=[UIColor whiteColor];

    [self.view addSubview:webView_];     
    self.view.backgroundColor=[UIColor blackColor]; 
    //隱藏灰影 
    for(UIView *v in [[[webView_ subviews] objectAtIndex:0] subviews]) 
    { 
        if([v isKindOfClass:[UIImageView class]]) 
        { 
            v.hidden = YES; 
        } 
    } 
    //拖動事件 
    UIScrollView* scrollView = [webView_.subviews objectAtIndex:0]; 
    if (scrollView && [scrollView isKindOfClass:[UIScrollView class]]) 
    { 
        scrollView.delegate = self; 
    } 
    //圓角 
    [[webView_ layer] setCornerRadius:10]; 
    [webView_ setClipsToBounds:YES]; 
    [[webView_ layer] setBorderColor:[[UIColor blackColor] CGColor]]; 
    //[[webView_ layer] setBorderWidth:2.75];

[(UIScrollView *)[[webview subviews] objectAtIndex:0] setBounces:NO];

24. 取得選中的內容

     給UIWebView增加類別

     - (NSString *)selectedText { 
    return [self stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"]; 
}

25.iphone web框架

    iUi  http://code.google.com/p/iui/   它是一個javascript和css庫,用於在網頁中模擬iphone的外觀和感覺。雖然是專爲iphone設計的UI,但在android上90%以上的功能是完全可以使用的,因爲android和iphone一樣,都是基於webkit瀏覽器的系統。 
iUI框架:用Eclipse開發iOS Web應用程序 
http://www.61ic.com/Mobile/iPhone/201203/41389.html

26.[iOS]給UIWebView頭尾插入自定義View

     http://blog.cnbang.net/tech/1784/

     示例代碼下載:

     https://github.com/bang590/iOSPlayground/tree/master/TWebview

     11個基本的移動Web編程工具

     http://developer.51cto.com/art/201107/273822.htm

27.iOS 5中safari帶來的新特性

http://www.qianduan.net/ios-5-brings-new-features-in-safari.html

28.HTML5 Showcase

     http://www.apple.com/html5/showcase/typography/

 轉自:http://www.cnblogs.com/dukewell/archive/2012/12/21/2827948.html

摘自:http://blog.csdn.net/andyweike/article/details/6077279

發佈了16 篇原創文章 · 獲贊 1 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章