id | title | brief | sdk | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
055FA463-E40B-6A58-7E19-4C47393B4884 |
Load Local Content |
This recipe shows how to load a local web page in a UIWebView control. |
|
To show local Html content in a UIWebView
:
- Add the files to your Xamarin.iOS project - in this example the HTML, images and style sheets have all been placed inside a Content folder in the project. Remember to set the Build Action to BundleResource for all files.
- Create a
UIWebView
and add it to a view:
webView = new UIWebView (View.Bounds);
View.AddSubview(webView);
- Load the file using
NSUrlRequest
andNSUrl
classes:
// Note the Content folder is where we placed the files
string fileName = "Content/Home.html"; // remember case-sensitive
string localHtmlUrl = Path.Combine (NSBundle.MainBundle.BundlePath, fileName);
webView.LoadRequest(new NSUrlRequest(new NSUrl(localHtmlUrl, false)));
webView.ScalesPageToFit = false;
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));