Last active
February 6, 2025 10:12
-
-
Save cscouto/fb49c0e8dc48c266ec76ee198c247a07 to your computer and use it in GitHub Desktop.
SWIFT - Observe contentSize fro the tableView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would add it on
viewDidLoad
and remove it ondeinit
instead.