Swift内置有kvo监视属性变化的能力。而我们常常需要监视某些属性的变化,比如在首先下拉刷新时,就是需要监视contentSize的变化。如下代码,可以直接拷贝使用:
private func addObserver() {
tableView?.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
}
private func removeAbserver() {
tableView?.removeObserver(self, forKeyPath:"contentSize")
}
var curentContentHeight : CGFloat = 0
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard tableView.isUserInteractionEnabled else {
return
}
print(tableView.contentSize.height)
curentContentHeight = tableView.contentSize.height
self.frame.origin.y = curentContentHeight
}复制代码
这样的做法,不需要使用第三方库(比如KVOController),测试起来是非常方便的。