# KVO 监听不到 WKWebView 的高度变化

**URL:** <https://www.shiqidu.com/t/topic/631>\
**Category:** 开发调优\
**Tags:** Swift\
**Created:** [August 29, 2019, 9:26am UTC](https://www.shiqidu.com/t/topic/631 "2019-08-29T09:26:50Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
**Post date:** [August 29, 2019, 9:26am UTC](https://www.shiqidu.com/t/topic/631/1 "2019-08-29T09:26:50Z")

</div>

使用 WKWebView 加载 H5 页面，想要回去到 H5 页面的高度，然后通过 kvo 监听 H5 高度，代码如下：

```swift
contentView.scrollView.addObserver(self, forKeyPath: "contentSize", options: [.new], context: nil)

```

但是怎么都监听不到变化

```swift
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
	guard let changes = change else {
		return
	}
	let newValue = changes[NSKeyValueChangeKey.newKey] as? Double ?? 0
	print("kvo height: \(newValue)")
}

```

这样打印高度，怎么怎么打印，都是 0.0，好神奇，为什么监听不到变化呢。

百思不得其解的时候发现，原来是我在添加 webview 的时候，就把高度写死成 841 了，如果 H5 页面的小于 841，内容就不足以撑开 webview, 所以我通过 JS 获取到的高度就是 841，所以导致 KVO 监听不到变化，自己手贱，记录一下，防止下次再踩坑。
