![](/img/trans.png)
[英]Dynamically set UIScrollView and UITableView height by its content
[英]How to set UITableView height according to its content height?
我有一个关于UITableView
的问题。
我想根据我的单元格内容高度让 tableView 高度。
所以,我成功地使用了以下代码。
DispatchQueue.main.async {
var frame = self.tableView.frame
frame.size.height = self.tableView.contentSize.height
self.tableView.frame = frame
}
但是当我有很多数据要显示时,我的内容会超出屏幕。
并且 tableView 也在屏幕外。
有任何想法来设置它的约束并且不要让它超出屏幕。
我想在tableView底部布局和superView底部布局之间设置15。
我使用 SnapKit 来设置自动布局。
//I want to set this one is the biggest frame size. Other contents I can scroll the tableView to show the data.
tableView.snp.makeConstraints { (make) in
make.top.equalTo(self.topLayoutGuide.snp.bottom)
make.left.equalTo(10)
make.right.equalTo(-10)
make.bottom.equalTo(-15)
}
您可以创建一个自定义UITableView
:
class AutomaticHeightTableView: UITableView {
override var contentSize: CGSize {
didSet {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
self.layoutIfNeeded()
return CGSize(width: UIViewNoIntrinsicMetric, height: contentSize.height + 20)
}
}
然后将您的UITableView
类设置为AutomaticHeightTableView
。
该解决方案的灵感来自于在 stackoverflow 上找到的答案。
我已经使用以下方法解决了类似的问题。 您只需要几行代码。
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
private func setupTableView() {
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
}
只需为 UITableView 设置一个估计的行高,然后将 rowHeight 设置为 UITableViewAutomaticDimension。
也许你可以限制表格框架的高度,确保不超过它的超级视图,像这样修改你的代码:
DispatchQueue.main.async {
if let superViewHeight = self.tableView.superView?.bounds.maxY {
let maxHeight = superViewHeight - self.tableView.frame.minY
var frame = self.tableView.frame
frame.size.height = min(self.tableView.contentSize.height, maxHeight)
self.tableView.frame = frame
}
}
代码工作:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tblHeightConstraint: NSLayoutConstraint! // tableView Height Constraint
@IBOutlet weak var tblView: UITableView!
var tblMaxHeight : CGFloat = 50
override func viewDidLoad() {
super.viewDidLoad()
let navHeight = (self.navigationController?.navigationBar.frame.size.height)! + UIApplication.shared.statusBarFrame.size.height
tblMaxHeight = self.view.frame.size.height - 40 - navHeight
}
override func viewDidLayoutSubviews(){
tblHeightConstraint.constant = min(tblMaxHeight, tblView.contentSize.height)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 24
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = "Row: #\(indexPath.row)"
return cell!
}
}
对 tableView 的约束:
输出 :
你有没有尝试过
self.tableView.invalidateIntrinsicContentSize()
https://developer.apple.com/documentation/uikit/uiview/1622457-invalidateintrinsiccontentsize
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.