Skip to content

Instantly share code, notes, and snippets.

@efremidze
Created June 7, 2017 02:29
Show Gist options
  • Save efremidze/d836e1ecc5f0990c935ae47ef7ac32c7 to your computer and use it in GitHub Desktop.
Save efremidze/d836e1ecc5f0990c935ae47ef7ac32c7 to your computer and use it in GitHub Desktop.
class ResizingTableView: UITableView {
private var heightConstraint: NSLayoutConstraint?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.addObserver(self, forKeyPath: #keyPath(contentSize), options: .new, context: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
self.removeObserver(self, forKeyPath: #keyPath(contentSize), context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(contentSize) {
_ = heightConstraint.map { NSLayoutConstraint.deactivate([$0]) }
heightConstraint = self.heightAnchor.constraint(equalToConstant: contentSize.height)
_ = heightConstraint.map { NSLayoutConstraint.activate([$0]) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment