2016-10-01 21 views
1

我的項目中有一個WebView。它可以有動態的html內容。現在我已經爲WebView提供了固定的寬度和高度,並且它可以滾動。但我想通過動態增加WebView的高度來移除滾動。竅門根據動態內容展開Xamarin Form WebView

有什麼辦法像創建自定義渲染器或什麼東西?

示例代碼

var webvw = new Webview(); 
var htmlSource = new HtmlWebViewSource(); 
htmlSource.Html = @"<html>" + 
       "<head>" + 
       "<style type=\"text/css\">" + 
       "@font-face {" + 
       "font-family: Roboto-Medium;" + fntsrc + "}" + 
       "html,body{margin:0px;}" + 
       "body {" + 
       "font-family: Roboto-Medium;" + 
       "font-size: 12px" + 
       "text-align: left;" + 
       "color: #acacac;" + "}" + 
       "body :first-child{" + 
       "font-family: Roboto-Medium;" + 
       "font-size: 12px" + 
       "font-weight: 300;" + 
       "line-height: 24px;" + 
       "text-align: left;" + 
       "color: #ffffff;" + "}" + 
       "</style>" + 
       "</head>" + 
       "<body style=\"background-color: transparent;\" >" + 
       dynamicContent + "</body>" + "</html>"; 
       webvw.Source = htmlSource; 
       webvw.WidthRequest = 500; 
       webvw.HeightRequest = 500; 

SatackLayout webContnet=new StackLayout{ 
    VerticalOptions=LayoutOption.FillAndExpand, 
    Orientation=StackOrientation.Vertical 
}; 

回答

1

有一種方式,但它是複雜的。 WebView不會自動調整其內容大小,因此唯一的辦法就是如果內容通知您的代碼有多大。

要做到這一點,您將需要Invoke C# from Javascript

它是一個稍微複雜的過程,您需要一個CustomRenderer,並且還需要在每個本地項目中設置屬性。按照上面的鏈接逐步指導如何做到這一點。

的JavaScript調用像這樣得到的高度

var body = document.body, 
    html = document.documentElement; 

var height = Math.max(body.scrollHeight, body.offsetHeight, 
         html.clientHeight, html.scrollHeight, html.offsetHeight); 

然後當它返回,您的WebView設置爲高。您可能還需要等到NavigationCompleted事件發生之後再執行此操作,以確保內容已加載到您的WebView中。

+0

感謝您指出方向。我以其他方式做了。 – Atul

+0

@Atul你是怎麼做到的?謝謝 – Rexxo

+0

@Atul有沒有機會提供詳細信息? –

1

確定這裏是我的「如果它看起來很愚蠢,但它的作品不愚蠢」-answer。

我遇到了同樣的問題,並尋找一種方法來獲得可能的身高。

我現在的解決方案是用costum renderes創建一個標籤來轉換html代碼。該標籤有一個屬性的高度和寬度;)

所以我創建標籤,把它放在一個StackLayout(它需要呈現),獲取大小的WebView,從StackLayout中刪除標籤,並添加現在具有完美大小的WebView :)

webView = new WebView(); 
var htmlSource = new HtmlWebViewSource(); 
htmlSource.Html = htmlCode; 
webView.Source = htmlSource; 

tmpLable = new HyperLinkLabel { 
    Text = htmlCode, 
}; 

stackLayout.Children.Add(tmpLable); 

webView.WidthRequest = tmpLable.Width; 
webView.HeightRequest = tmpLable.Height; 

stackLayout.Children.Remove(text); 

stackLayout.Children.Add(web);