如何在swift中更改现有HTML字符串的样式?

时间:2017-10-11 03:41:43

标签: html ios swift uiwebview

我从Web服务获取HTML字符串并将其加载到UIWebView上。一个示例html字符串是这样的。

" <div class='wg-rs-workAnniversary'> <div class='greetingtext'><span class='years work-years'>1 <sup>-</sup></span> <span class='event'>Work <br> Anniversary</span></div> <input type='hidden' class='hid-work-years' value='1'/> </div> <div class='wg-rs-btext work-years'>ABC Employee celebrates his 1<sup>-</sup> work anniversary today</div>"

我加载后它只是一个黑色文字。我想增加这些文字的大小,改变颜色并将其居中于UIWebView。我怎么能在swift中做到这一点?请帮帮我。

1 个答案:

答案 0 :(得分:1)

哟可以通过在html字符串中附加样式来实现。

let htmlText = " <div class='wg-rs-workAnniversary'> <div class='greetingtext'><span> class='years work-years'>1 <sup>-</sup></span> <span> class='event'>Work <br> Anniversary</span></div> <input type='hidden'> class='hid-work-years' value='1'/> </div> <div class='wg-rs-btext> work-years'>ABC Employee celebrates his 1<sup>-</sup> work anniversary> today</div>"   
let htmlTextWithStyle = htmlText + ("<style>body{font-family: '\(UIFont.systemFont(ofSize: 12.0))'; font-size:\(14.0);}</style>")

要使其居中,您可以在html字符串中添加以下内容

"<style type='text/css'>html,body {margin: 0;padding: 0;width: 100%;height: 100%;}html {display: table;}body {display: table-cell;vertical-align: middle;padding: 20px;text-align: center;-webkit-text-size-adjust: none;}</style>"