我的代码中有一个UITableView
tableView = UITableView(frame: CGRect(x:0,y:0,width:0,height:0))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellReuseIdentifier")
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as UITableViewCell!
cell.textLabel?.text = self.comments[indexPath.row]
return cell
}
我想给这个UITableView一个动态高度。我尝试了两件事
tableView.estimatedRowHeight = 88.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true
他们都没有奏效。
设置UITableViewAutomaticDimension
后,无需使用以下代码行
tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true
问题可能是您的autolayout
约束,这似乎不合适。因此,您需要确保在tableViewCell
对象中正确固定了前导、尾随、顶部和底部约束。
注意:- 如果您使用的是 UILabel,则设置行数 = 0。