swift 使用“自动布局”将UITableView的高度设置为其内容的高度
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 使用“自动布局”将UITableView的高度设置为其内容的高度相关的知识,希望对你有一定的参考价值。
class IntrinsicTableView: UITableView {
override var contentSize:CGSize {
didSet {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return CGSize(width: UIViewNoIntrinsicMetric, height: contentSize.height)
}
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
tableView.layer.removeAllAnimations()
tableHeightConstraint.constant = tableView.contentSize.height
UIView.animate(withDuration: 0.5) {
self.updateConstraints()
self.layoutIfNeeded()
}
}
以上是关于swift 使用“自动布局”将UITableView的高度设置为其内容的高度的主要内容,如果未能解决你的问题,请参考以下文章