在渲染WKWebView内容

时间:2017-10-27 15:06:44

标签: xamarin xamarin.ios uiscrollview wkwebview

感谢您查看我的问题。目前,我有几个输入字段和一个嵌入在UIScrollView中的WKWebView。在任何事件触发之前,所有子视图都适合滚动视图,没有任何问题。我根据位于WKNavigationDelegate的DidFinishNavigation委托中捕获的document.body.scrollHeight动态设置WK的高度。设置WK的高度后,WK会超出可查看的内容。这是我尝试强制滚动视图调整自身大小的代码。

[Export("webView:didFinishNavigation:")] public async void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{

        //get the webView's initial height
        var initialHeight = webView.Frame.Height;

        //get height of HTML's document.body.scrollHeight
        var contentHeight = await GetContentHeight();

        //create new frame for webview
        CGRect newWebViewFrame = new CGRect(webView.Frame.X, webView.Frame.Y, webView.Frame.Width, contentHeight);

        //set webview's frame
        webView.Frame = newWebViewFrame;

        //get the difference of webView's initial height and webView's current height
        var differenceInHeight = contentHeight - initialHeight;

        //create new cgrect and set the height to svMain's height + the difference in height of the HTML document
        CGRect newScrollViewFrame = new CGRect(0, 0, svMainScroller.Frame.Width, svMainScroller.Frame.Height + differenceInHeight);

        //set MainScroller's frame
        svMainScroller.Frame = newScrollViewFrame;

        //force scrolling
        svMainScroller.ScrollEnabled = true;

        //scrolling should be handled in the main scroller
        webView.ScrollView.ScrollEnabled = false;

        svMainScroller.SizeToFit();
    }

所需的效果是使滚动视图能够滚动到新定义的高度的末尾。关于如何做到这一点的任何提示将不胜感激。

1 个答案:

答案 0 :(得分:0)

更新滚动视图的框架是个问题。我的猜测是,如果框架足够大以包含所有内容,那么就不需要滚动。因此,我更新了滚动视图的ContentSize,而不是更新其框架。

svMainScroller.ContentSize = new CGSize(View.Frame.Width, View.Frame.Height + differenceInHeight);

另外,作为旁注,请确认wkwebview是作为子视图添加到滚动视图而不是主视图。