I have an issue regarding the height of UITableViewCell
in Swift: The height of the UITableViewCell
should be updated with the embedded HTML code in WKWebView
, but it doesn't.
import UIKit
import WebKit
class SocialVideoPlayer: UITableViewCell, WKUIDelegate {
var url: URL!
var scroll = false
var variable = (String)()
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var view: UIView!
@IBOutlet weak var webviewheight: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
webView.scrollView.isScrollEnabled = scroll
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
let e = "<iframe src=\"https://www.facebook.com/plugins/post.php?href=\(variable)\" style=\"background: white none repeat scroll 0% 0%; max-width: 400px; width: calc(100% - 2px);border-radius: 3px; border: none; box-shadow: none; display: block; margin: 0px 0px 12px; min-width: 326px; padding: 0px;\" allowtransparency=\"true\"></iframe>"
webView.loadHTMLContent(e)
}
override func layoutSubviews() {
super.layoutSubviews()
webView.navigationDelegate = self
webView.uiDelegate = self
webView.backgroundColor = UIColor.clear
webView.isOpaque = false
webView.contentMode = .scaleAspectFill
webView.sizeToFit()
webView.autoresizesSubviews = true
}
}
extension WKWebView {
func loadHTMLContent(_ htmlContent: String) {
let htmlStart = "<!doctype html><meta charset='utf-8'/><head><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></head><body><div>"
let htmlEnd = "</div></body></html>"
let htmlString = "\(htmlStart)\(htmlContent)\(htmlEnd)"
loadHTMLString(htmlString, baseURL: nil)
}
}
extension SocialVideoPlayer: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
webView.evaluateJavaScript("document.body.scrollHeight") { (result, error) in
if error == nil {
guard let height = result as? CGFloat else { return }
self.webviewheight.constant = height
NotificationCenter.default.post(name: Notification.Name("fbFinishload"), object: "")
}
}
}
})
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard case .linkActivated = navigationAction.navigationType,
let url = navigationAction.request.url
else {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
UIApplication.shared.open(url)
}
}