2012-10-29 62 views
22

我有一個使用loadHtmlString函數加載數據的uiwebview。事情是我從sqlite數據庫加載數據,每次加載不同長度的字符串時,Web視圖自然會獲得不同的高度。
現在我需要知道每次uiwebview的確切高度,以便在webView下正確加載imageView。 我試過獲取UIWebView內容的高度

- (void)webViewDidFinishLoad:(UIWebView *)aWebView { 
    CGRect frame = aWebView.frame; 
    frame.size.height = 1; 
    aWebView.frame = frame; 

    CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero]; 
    frame.size = fittingSize; 
    aWebView.frame = frame; 

    NSLog(@"Size: %f, %f", fittingSize.width, fittingSize.height); 
} 

但我總是得到相同的結果。我需要知道如何在每次加載時動態獲取Web視圖的高度。 THX

回答

-3

這不是處理這種情況的正確方法;而不是在圖像視圖中加載圖像,並且必須始終牢記高度和寬度以及所有這些東西......最簡單和最可靠的解決方案只是將圖像加載到html字符串中,就是這樣!只要確保baseURL是這樣的,無論你採取什麼方向,一切都會好的:

NSString* extension = @"gif"; 
    NSString* strRR = [NSString stringWithFormat:@"%@.%@", authorNAme2,extension]; 
    NSString *path = [[NSBundle mainBundle] bundlePath]; 
    //NSLog(@"This is the path %@", path); 
    NSURL *baseURL = [NSURL fileURLWithPath:path]; 
    // NSLog(@"this is the base URL %@",baseURL); 

    NSString *cachePath = [NSString stringWithFormat:@"%@/%@", path,strRR]; 

      NSString * htmlString = [NSString stringWithFormat:@"\ 
            <html>\ 
            <table width='100%%'>\<tr>\<td>\ 
            <body>\ 
            <p style = 'font-size:30px;'> %@ <\p>\ 
            </td></tr><tr><td><br></td></tr><tr><td align ='center'><br><img src='%@' width='60%%' \></td></tr></body>\ 
            </table>\ 
            </html>",authorNAme , cachePath]; 



      //   NSString *selection = [WebV2 stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"]; 
      //   NSLog(@"*/*/*/*/**/*/*/*/*/*/*//*/ This is your selection mate %@" , selection); 




      WebV.opaque = NO; 
      WebV.backgroundColor = [UIColor clearColor]; 
      [self.WebV setScalesPageToFit:YES]; 
      [self.WebV loadHTMLString:htmlString baseURL:baseURL]; 
29

您可以通過訪問Web視圖的scrollView屬性來獲取在Web視圖內容的高度:

NSLog(@"%f",myWebView.scrollView.contentSize.height); 
+1

比JS更好。也爲你+1。 – 2012-10-29 14:01:50

+6

我試了一下,但是同樣的數字一直在繼續...即使我有一個2字的段落,我得到737,所以它沒有工作:S –

+0

@EliasRahme你能更好地解釋你在這裏試圖達到什麼。我上面列出的代碼*是*如何跟蹤webview中內容的大小。 –

45

試試這個

NSString *result = [webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"]; 

int height = [result integerValue]; 
在webViewDidFinishLoad方法

+0

會提出這個建議。 +1。 – 2012-10-29 14:01:20

+0

我該如何獲得變量的結果?我沒有看到你的建議的結果,我該如何處理它?我是新的感謝您的理解 –

+2

@EliasRahme您將結果返回到返回的字符串:'NSString * result = [webView stringByEvaluatingJavaScriptFromString:@「document.body.offsetHeight;」];'將結果'字符串轉換爲int可以使用:'int height = [result integerValue];' –

相關問題