Skip to content

Instantly share code, notes, and snippets.

@cscouto
Last active March 19, 2024 15:05
Show Gist options
  • Save cscouto/fb49c0e8dc48c266ec76ee198c247a07 to your computer and use it in GitHub Desktop.
Save cscouto/fb49c0e8dc48c266ec76ee198c247a07 to your computer and use it in GitHub Desktop.
SWIFT - Observe contentSize fro the tableView
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var heightTableView: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.addObserver(self,
forKeyPath: "contentSize",
options: .new,
context: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
tableView.removeObserver(self,
forKeyPath: "contentSize")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
if let obj = object as? UITableView,
obj == self.tableView &&
keyPath == "contentSize" {
heightTableView.constant = tableView.contentSize.height
}
}
}
}
@tgmain
Copy link

tgmain commented Aug 3, 2018

terbaique (y)

@TaLinh
Copy link

TaLinh commented Sep 12, 2020

This code has potential problem in case where this VC pushes/presents another screen. TableView observer is removed immediately and will not be added back when the VC reappears

@allanalves
Copy link

I would add it on viewDidLoad and remove it on deinit instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment