I'm trying to have a WKWebView load an image from data however it's making the scrollView's contentSize much larger than the actual image. Can some explain what's going on?
Here's how I'm loading the image from a data class.
if let image = UIImage(data: data) {
print("image size:", image.size)
}
webView.load(data, mimeType: mimeType, characterEncodingName: "", baseURL: url)
The navigationDelegate then returns me the contentSize.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("content size:", webView.scrollView.contentSize)
}
The output I get is the following. The image is centered at the top of the oversized scrollView.
image size: (133.0, 354.0)
content size: (834.0, 988.0) // same size as my WKWebView
I want to have the scrollView size match my image. Thanks for any advice.
Edit 1: I tried various solutions to resize using the smaller contentSize however the scrollView didn't seem to respond. For now I'm at the following:
if let image = UIImage(data: data), image.size.width < webView.bounds.width && image.size.height < webView.bounds.height, let contentView = webView.scrollView.subviews.first {
let imageView = UIImageView(image: image)
imageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(imageView)
let constraints = [
imageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
]
NSLayoutConstraint.activate(constraints)
} else {
webView.load(data, mimeType: mimeType, characterEncodingName: "", baseURL: me.url)
}