Xamarin.forms webview auto height with content

I am using a Webview and Label control on my page. I want to show the label once the WebView has scrolled to the end of its content. Here is an image showing what is happening:

enter image description here

The label always stays at the bottom.

I have tried this code:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <WebView Grid.Row="0"  Source="{Binding DetailHtml}"></WebView>
    <Label Grid.Row="1" Text="TIN LIÊN QUAN" TextColor="#5ea201" FontAttributes="Bold"/>
</Grid>

and this:

<StackLayout>
    <WebView Source="{Binding DetailHtml}"></WebView>
    <Label  Text="TIN LIÊN QUAN" TextColor="#5ea201" FontAttributes="Bold"/>
</StackLayout>

I also tried to use a custom renderer for WebView to set the height but it doesn't work:

[assembly: ExportRenderer(typeof(WebView), typeof(WebViewCustomRenderer))]
namespace SucKhoeGiaDinh.iOS.Renderers
{
    public class WebViewCustomRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
            Delegate = new ExtendedUIWebViewDelegate(this);
        }
    }

    public class ExtendedUIWebViewDelegate : UIWebViewDelegate
    {
        WebViewCustomRenderer webViewRenderer;

        public ExtendedUIWebViewDelegate(WebViewCustomRenderer _webViewRenderer = null)
        {
            webViewRenderer = _webViewRenderer ?? new WebViewCustomRenderer();
        }

        public override async void LoadingFinished(UIWebView webView)
        {
            if (webViewRenderer.Element is WebView wv)
            {
                await System.Threading.Tasks.Task.Delay(100); // wait here till content is rendered
                wv.HeightRequest = (double)webView.ScrollView.ContentSize.Height;
            }
        }
    }
}

It there another approach I could use to achieve this?

Upvotes: 4

Views: 7890

Answers (1)

I solved my problem.

<ScrollView >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <WebView Grid.Row="0"  Source="{Binding DetailHtml}" />
        <Label Grid.Row="1" Text="TIN LIÊN QUAN" TextColor="#5ea201" FontAttributes="Bold"/>
    </Grid>
</ScrollView>

and custom render webview to set height by content.

Upvotes: 3

Related Questions