【发布时间】:2019-03-05 13:39:50
【问题描述】:
我的 UITableView 嵌入在 UIView 中,我希望这个超级视图的高度根据表格视图具有的 UITableViewCells 的数量而变化。
也就是说,如果 tableView 有 1 个单元格,UIView 将是这个单元格的大小,如果有 2 个单元格,UIView 将增长到 2 个单元格的大小。
【问题讨论】:
标签: swift uitableview
我的 UITableView 嵌入在 UIView 中,我希望这个超级视图的高度根据表格视图具有的 UITableViewCells 的数量而变化。
也就是说,如果 tableView 有 1 个单元格,UIView 将是这个单元格的大小,如果有 2 个单元格,UIView 将增长到 2 个单元格的大小。
【问题讨论】:
标签: swift uitableview
如果您使用的是 Autolayout 约束,您只需更新 UITableView 的高度约束本身就可以了。
以下是基本步骤:
子类 UITableView:
class CustomTableView: UITableView {
var maximumTableViewHeight: CGFloat = UIScreen.main.bounds.size.height
private var heightConstraint: NSLayoutConstraint!
override func reloadData() {
super.reloadData()
self.heightConstraint.constant = min(self.contentSize.height, maximumTableViewHeight)
}
override func awakeFromNib() {
super.awakeFromNib()
self.heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1, constant: 0)
self.addConstraint(heightConstraint)
}
}
具有我们的子类CustomTableView的故事板
然后你的视图控制器:
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet var tableView: CustomTableView!
private let cellIdentifier = "Cell"
var dataSource: [Int] = [1, 2, 3] {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.maximumTableViewHeight = 400 // Adjust as per your max height
}
@IBAction func addCell(_ sender: Any) {
let count = self.dataSource.count + 1
self.dataSource.append(count)
let scrollToIndexPath = IndexPath(row: count - 1, section: 0)
DispatchQueue.main.async {
self.tableView.scrollToRow(at: scrollToIndexPath, at: .bottom, animated: false)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
}
cell.textLabel?.text = "Value: " + String(dataSource[indexPath.row])
return cell
}
}
产生:
注意红色区域,这是UITableView的父UIView
【讨论】: