user1960169 user1960169 - 5 months ago 17
Swift Question

HTML Formatting in swift

I am getting a content like this from my web service

<Strong>some unicode characters</Strong>
<iframe src="https://www.youtube.com/embed/<some_ID>" width="640" height="480" frameborder="0" allowfullscreen="allowfullscreen"></iframe>


When I load this string directly to the
UIWebView
it is black. But I want to make it in white color.


  1. How to change the color of this in swift

  2. Also need to change the width of this video to current
    UIView
    width



How can I do this?

Answer

You can use Javascript to add a bit of style and resize the video:

override func viewDidLoad() {
    super.viewDidLoad()

    let html = "..."
    webView.delegate = self
    webView.loadHTMLString(html, baseURL: nil)
}

func webViewDidFinishLoad(webView: UIWebView) {
    let url = NSBundle.mainBundle().URLForResource("script", withExtension: "js")!
    let javascript = try! String(contentsOfURL: url)

    webView.stringByEvaluatingJavaScriptFromString(javascript)
}

And the content of script.js:

var title = document.body.getElementsByTagName('strong')[0]
title.style.color = 'blue'
title.style.display = 'block'

var iframe = document.body.getElementsByTagName('iframe')[0]
iframe.style.width = '100%'
iframe.height = document.body.offsetHeight - title.offsetHeight