Created
September 17, 2018 14:09
-
-
Save aibobrov/e6c93867f83ee2131c5f4773f2cf617e to your computer and use it in GitHub Desktop.
Self sized UITableView
This file contains 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
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