Show html description in UIWebView in a better way
Let’s take a look on the output above, the Event Description content.
Yes, it can achieved by using UILabel
, but somehow HTML would be easy
to construct the format. Thus I’m showing a demo on how to use UIWebView
to achieve this.
This is using auto-layout
Add constraint
(I assumed that you know how to add constraint through storyboard)
Now add 4 or 5 constraints to UIWebView
, make sure the Height constraint is added, you can put any value you like.
Set UIWebViewDelegate
to self
ViewController.swift
1 | class ViewController: UIViewController, UIWebViewDelegate { |
Go back the storyboard, hold the right-click and drag it over to the controller
Disable scroll, format subview
Here to disable the scroll, hide the scroll indicator, disable bounces,
clear the UIWebView
background
ViewController.swift
1 | self.descriptionWebView.scrollView.scrollEnabled = false |
Add content & update height
Add a wrapper to the content (use main-wrapper
here)
ViewController.swift
1 | self.descriptionWebView.loadHTMLString("<div id='main-wrapper'>\(html)</div>", baseURL: nil) |
Implement the UIWebViewDelegate
1 | func webViewDidFinishLoad(webView: UIWebView) { |
The output would be
1 | webView content height 187.0 |
The UIWebView
constraints here has only 1, thus I assumed that the first
constraint is the Height constraint, by changing the value of the first
constraint, the height of UIWebView
will be changed.
Open link by using safari (optional)
Now, if you want user to open safari when they click on the link, implement
another method
1 | func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { |
Completed
Make sure the UIWebView
is inside UIScrollView
. As by using auto-layout,
the UIScrollView
content height will be expand based on its subviews.