Обновить высоту WKWebViewIOS

Программируем под IOS
Ответить
Anonymous
 Обновить высоту WKWebView

Сообщение Anonymous »

Мне нужна помощь в обновлении высоты UITableViewCell на основе высоты содержимого WKWebKitView.
Я написал код, чтобы получить высоту на основе document.body.offsetHeight не сработало, поскольку добавлялось пустое пространство в конце webView.
Поэтому я использовал следующий метод.

Код: Выделить всё

extension PDDescriptionCell: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.summaryHeight?.constant = 0

self.contentView.layoutIfNeeded()
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.summaryHeight?.constant = webView.scrollView.contentSize.height

if let tableView = self.superview as? UITableView {
tableView.beginUpdates()
tableView.endUpdates()
}

self.contentView.layoutIfNeeded()
}
}
Проблема в том, что PDDescriptionCell является частью ProductDetail UITableViewController, у которого есть другие tableViewCells, и этот PDDescriptionCell находится в строке 3. Как только я открываю ProductDetail и прокручиваю до строки 3 для PDescriptionCell, высота такая же, как и в файле xib. Однако tableView обновляется. но правильная высота для PDDscriptionCell не обновляется. Если бы я прокрутил вверх до строки 1, а затем вернулся к строке 3, для PDescriptionCell обновилась бы правильная высота.
Как мне убедиться, что высота строки 3 для PDescriptionCell обновлена, когда строка 3 находится на самом экране при таком способе определения высоты?
Полный код для PDescriptionCell:

Код: Выделить всё

class PDDescriptionCell: UITableViewCell {
var product: ProductModel? {
didSet {
if let product = product {
print(product.summary)

loadContent(product.summary)
}
}
}

IBOutlet weak var summaryView: WKWebView!
IBOutlet weak var summaryHeight: NSLayoutConstraint!

private let configuration = WKWebViewConfiguration()

override func awakeFromNib() {
super.awakeFromNib()

print("awake from nib")

contentView.backgroundColor = .background1

summaryView.navigationDelegate = self

let preference = WKWebpagePreferences()

preference.preferredContentMode = .mobile
preference.allowsContentJavaScript = true

let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences = preference

if let product = product {
_ = WKWebViewConfiguration()

print("HTML string is loaded")

self.summaryView.loadHTMLString(product.summary, baseURL: nil)
self.loadContent(product.summary)
}
}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}

private func loadContent(_ content: String) {
let styledHTML = """


 body { font-size: 30px; /\* Change the font size for the body as needed \*/ font-family: -apple-system; /\* Use the system font \*/ } table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #dddddd; text-align: left; padding: 8px; font-size: 20px; /\* Change the font size for table cells as needed \*/ } th { background-color: #f2f2f2; } img { width: 100%; /\* Set the width of images to 100% \*/ height: auto; /\* Set the height of images to auto to maintain aspect ratio \*/ margin-bottom: 50px; /\* Add space below each image \*/ } .semibold { font-weight: 600; /\* Set font weight to semibold \*/ } 
 window.onload = function() { var body = document.body; var html = document.documentElement; var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); window.webkit.messageHandlers.iOS.postMessage(height); } 


\(content)


"""

// Load the styled HTML content into the WKWebView
self.summaryView.loadHTMLString(styledHTML, baseURL: nil)
}
}

extension PDDescriptionCell: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.summaryHeight?.constant = 0

self.contentView.layoutIfNeeded()
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.summaryHeight?.constant = webView.scrollView.contentSize.height

if let tableView = self.superview as? UITableView {
tableView.beginUpdates()
tableView.endUpdates()
}

self.contentView.layoutIfNeeded()
}
}
Я пытался получить высоту с помощью AssessmentJavaScript("document.readyState") и AssessmentJavaScript("document.body.scrollHeight"), но в итоге получилось добавление пустое место в конце веб-просмотра. Я собираюсь использовать тот же код для получения высоты, поскольку он корректно работает при обновлении высоты, но не обновляется в нужное время.


Подробнее здесь: https://stackoverflow.com/questions/784 ... -wkwebview
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»