question

EJ-5254 avatar image
0 Votes"
EJ-5254 asked EJ-5254 commented

iOS WkWebViewRenderer width

Hi,

In old UIWebView you could set ScalesPageToFit, but new WkWebViewRenderer doesn't have this property. I want to make WebView width to be same size as device width, so no horizontal scrolling.

No matter what I've tried (injecting "meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no'" into html) and so on, if content width is greater than device it allows to horizontally scroll.

Any ideas how can I fix this? Thanks in advance!

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered EJ-5254 commented

Hello,​

Welcome to our Microsoft Q&A platform!

In old UIWebView you could set ScalesPageToFit, but new WkWebViewRenderer doesn't have this property.

Try using the following code to make the webView to fit the screen in the custom WkWebViewRenderer class.

public class CustomWebViewRenderer : WkWebViewRenderer
{
    const string JavaScriptFunction = ...;
    WKUserContentController userController;

    public CustomWebViewRenderer() : this(new WKWebViewConfiguration())
    {
    }

    public CustomWebViewRenderer(WKWebViewConfiguration config) : base(config)
    {
        userController = config.UserContentController;
        var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
        userController.AddUserScript(script);
        config.UserContentController = userController;
        WKWebView webView = new WKWebView(Frame, config);
    }
}


Best Regards,

Jarvan Zhang



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello,

Thank you for the reply. Does the line

const string JavaScriptFunction = ...;

should contain something instead of three dots at the end?

0 Votes 0 ·

@EJ-5254 Sorry for my mistake, here is the complete code about the 'JavaScriptFunction'.

string JavaScriptFunction  = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"
0 Votes 0 ·

Hello,

Thank you, it works now, content is sized to screen width!

0 Votes 0 ·