Dynamically Setting WebView Height in .NET MAUI for Varying HTML Content on iOS Platform

Sreejith Sreenivasan 941 Reputation points
2025-02-19T06:38:28.09+00:00

I am using a custom WebView in my .NET MAUI application to display dynamic HTML content on iOS. The HTML content changes daily, and I need to adjust the height of the WebView accordingly.

Custom WebView Renderer (iOS)

Here’s my custom WebViewRenderer implementation:

public class MyWebViewRenderer : ViewRenderer<MyWebView, WKWebView>
{
    WKWebView _wkWebView;

    protected override void OnElementChanged(ElementChangedEventArgs<MyWebView> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            var config = new WKWebViewConfiguration();
            config.AllowsInlineMediaPlayback = true;
            _wkWebView = new WKWebView(Frame, config);
            //transparent background
            _wkWebView = new WKWebView(CGRect.Empty, config);
            _wkWebView.BackgroundColor = UIColor.Clear;
            _wkWebView.ScrollView.BackgroundColor = UIColor.Clear;
            _wkWebView.ScrollView.ScrollEnabled = false;
            _wkWebView.Opaque = false;
            _wkWebView.NavigationDelegate = new MyNavigationDelegate();
            SetNativeControl(_wkWebView);

            if (Device.Idiom == TargetIdiom.Tablet)
            {
                //when targeting on iPad, add this to force the iPad behavior
                _wkWebView.Configuration.DefaultWebpagePreferences.PreferredContentMode = WKContentMode.Mobile;
            }
            SetNativeControl(_wkWebView);
        }
    }

    public class MyNavigationDelegate : WKNavigationDelegate
    {
        public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
        {
            string fontSize = "";
            if (Device.Idiom == TargetIdiom.Phone)
            {
                fontSize = "500%"; // > 100% shows larger than previous
            }
            else if (Device.Idiom == TargetIdiom.Tablet)
            {
                fontSize = "320%"; // > 100% shows larger than previous
            }

            string injectCustomFontScript = @"
                let style = document.createElement('style');
                style.innerHTML = `
                    @font-face {
                        font-family: 'CustomFont';
                        src: url('Poppins-Light') format('truetype');
                    }
                    body, p, h1, h2, h3, h5, h6 {
                        font-family: 'CustomFont', sans-serif !important;
                        color: #313131 !important;
                    }
                    h4 {
                        font-family: 'CustomFont', sans-serif !important;
                        color: #679E18 !important;
                    }
                `;
                document.head.appendChild(style);
            ";

            string stringsss = String.Format(@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '{0}'", fontSize);
            WKJavascriptEvaluationResult handler = (NSObject result, NSError err) =>
            {
                if (err != null)
                {
                    System.Console.WriteLine(err);
                }
                if (result != null)
                {
                    System.Console.WriteLine(result);
                }
            };
            webView.EvaluateJavaScript(stringsss, handler);
            webView.EvaluateJavaScript(injectCustomFontScript, handler);
        }

    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == "Url")
        {
            string finalHtml = Element.Url.Replace("width=\"640\"", "width=\"1000\"");
            Control.LoadHtmlString(finalHtml, null);
        }
    }
}

XAML Code:

<local:MyWebView 
    x:Name="ios_web_view"
    Margin="0,5,0,0"
    Grid.Row="0"
    HorizontalOptions="FillAndExpand"
    VerticalOptions="FillAndExpand">
    <local:MyWebView.HeightRequest>
        <OnIdiom x:TypeArguments="x:Double">
            <OnIdiom.Phone>10000</OnIdiom.Phone>
            <OnIdiom.Tablet>15000</OnIdiom.Tablet>
            <OnIdiom.Desktop>10000</OnIdiom.Desktop>
        </OnIdiom>
    </local:MyWebView.HeightRequest>
</local:MyWebView>

I want the WebView height to automatically adjust based on the HTML content’s height instead of setting a fixed HeightRequest. Since the content changes daily, I cannot hardcode a specific height.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,942 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 71,686 Reputation points
    2025-02-19T22:40:39.4+00:00

    on the webview navigated event:

    https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/webview?tabs=macos

    your c# code would call the javascript to get the document size and adjust the size.

    var height = await _wkWebView.EvaluateJavaScriptAsync("document.documentElement.getBoundingClientRect().height");
    
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.