Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 624
Talha Ahmad Khan Avatar asked Dec 14 '22 06:12

Talha Ahmad Khan


2 Answers

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) {
            HTMLToBeReturned.removeRange(match)
            if let match2 = HTMLToBeReturned.rangeOfString("(?<=height=\")[^\"]+", options: .RegularExpressionSearch) {
                HTMLToBeReturned.removeRange(match2)
                let string2del = "width=\"\" height=\"\""
                HTMLToBeReturned = HTMLToBeReturned.stringByReplacingOccurrencesOfString( string2del, withString: "")
            }
        }

    }

    return HTMLToBeReturned
}
like image 129
Talha Ahmad Khan Avatar answered Jan 06 '23 22:01

Talha Ahmad Khan


You can add style to your HTML body :

let styleContent = "<html><head><style>img{width:100%;};</style></head>" 
+ "<body style='margin:0; padding:0;'>" + (your html body) + "</body></html>";
like image 44
sergio_veliz Avatar answered Jan 06 '23 22:01

sergio_veliz