Search code examples
htmliosswiftuiwebview

How to change the styles of existing HTML string in swift?


I am getting a HTML string from a web service and load it on an `UIWebView. A Sample html string is like this.

" <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>"

After I loaded it it is just a black text. I want to increase the size of these text, change the color and center it on the UIWebView. How can I do this in swift? Please help me.


Solution

  • Yo can do it by appending style in your html string.

    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>")
    

    To center it , You can add following in your html string

    "<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>"