Talha Ahmad Khan Talha Ahmad Khan - 7 months ago 124
iOS Question

Swift: How to change only <img> or image sizes in webView

I am getting HTML from a server and display it in a UIWebView.The "Scale Page to fit" option is not selected because of the requirement. The UIWebView width is equal to the screen width and height varies according to the content. The image tags in HTML contains some inline styling which are creating some problem in the view of webView.
Screenshots are attached

Some images with small size looks ok

Some images with large width and height go out of screen

in 1st Image you can see the image is small because of small size set to it's inline styling. But 2nd one has larger image, so the image goes out of bound.

Is there any way to control the width of the image to equal to the screen width/ UIWebview width ?


Here is the code that I used to omit the widths and heights in HTML. The uiwebview then adjusted the images within the screen width

func HTMLImageCorrector(HTMLString: String) -> String {
    var HTMLToBeReturned = HTMLString
    while HTMLToBeReturned.rangeOfString("(?<=width=\")[^\" height]+", options: .RegularExpressionSearch) != nil{
        if let match = HTMLToBeReturned.rangeOfString("(?<=width=\")[^\" height]+", options: .RegularExpressionSearch) {
            if let match2 = HTMLToBeReturned.rangeOfString("(?<=height=\")[^\"]+", options: .RegularExpressionSearch) {
                let string2del = "width=\"\" height=\"\""
                HTMLToBeReturned = HTMLToBeReturned.stringByReplacingOccurrencesOfString( string2del, withString: "")


    return HTMLToBeReturned