Skip to content

Instantly share code, notes, and snippets.

@aibobrov
Created September 17, 2018 14:09
Show Gist options
  • Save aibobrov/e6c93867f83ee2131c5f4773f2cf617e to your computer and use it in GitHub Desktop.
Save aibobrov/e6c93867f83ee2131c5f4773f2cf617e to your computer and use it in GitHub Desktop.
Self sized UITableView
import UIKit
class SelfSizedTableView: UITableView {
lazy var heightConstraint: NSLayoutConstraint = {
let constraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: bounds.height)
return constraint
}()
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
heightConstraint.isActive = true
addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
if let obj = object as? UITableView, obj == self && keyPath == "contentSize" {
heightConstraint.constant = contentSize.height
superview?.layoutIfNeeded()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment