mxmissile
mxmissile

Reputation: 11673

Load Local CSS File Into Xamarin IOS WebView?

I'm able to load a local HTML file into my WebView like this (this works fine):

var fileName = "Views/Default.html"; 
var localHtmlUrl = Path.Combine(NSBundle.MainBundle.BundlePath, fileName);
var url = new NSUrl(localHtmlUrl, false);
var request = new NSUrlRequest(url);
WebView.LoadRequest(request);

I'd like to reference a CSS file (also local) in my HTML file:

<link href="Content/style.css" rel="stylesheet">

The CSS file does exist inside of a Content folder, the build action is set to Content for said file.

How can I reference/load the CSS file in question via my html file? Possible?

UPDATE: Had css and html in separate folders. Put them both in a Content folder then updated the hrefs which solved the issue while using LoadRequest.

Upvotes: 2

Views: 2789

Answers (1)

Yuri S
Yuri S

Reputation: 5370

Check this link https://developer.xamarin.com/recipes/ios/content_controls/web_view/load_local_content/

Section Additional information

Html generated in code can also be displayed, which is useful for customizing the content. To display an Html string, use the LoadHtmlString method instead of LoadRequest. Passing the path to the Content directory helps the web view resolve relative Urls in the Html, such as links, images, CSS, etc.

// assumes you've placed all your files in a Content folder inside your app
string contentDirectoryPath = Path.Combine (NSBundle.MainBundle.BundlePath, "Content/");
string html = "<html><a href='Home.html'>Click me</a></html>";
webView.LoadHtmlString(html, new NSUrl(contentDirectoryPath, true));

Upvotes: 3

Related Questions