Swift 如何为UITableView指定动态高度
我的代码中有一个Swift 如何为UITableView指定动态高度,swift,uitableview,Swift,Uitableview,我的代码中有一个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.translatesAut
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
一旦设置了
UITableViewAutomaticDimension
tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true
问题可能是您的autolayout
约束似乎不合适。因此,您需要确保在tableViewCell
对象中正确固定了前导、尾随、顶部和底部约束
注意:-如果使用UILabel,则将行数设置为0
对于
UITableView
,我只有顶部、左侧和右侧约束,没有底部,在单元格内,除了文本之外,我没有任何内容。您也需要设置底部约束。否则,tableViewcell将无法正确调整大小。但这将自动定义其高度,不是吗?我尝试将其底部固定到其父UIView,但它只是调整到其父UIView的高度,因此如果具有适当的前导、尾随、顶部和底部约束,则自动标注将起作用。否则布局将不会自动调整其高度。此外,您还需要确保UILabel的行数=0i对于UITableView
,只有顶部、左侧和右侧约束,而没有底部,并且在单元格内,除了文本之外,我没有任何内容。您还需要设置底部约束。否则,tableViewcell将无法正确调整大小。但这将自动定义其高度,不是吗?我尝试将其底部固定到其父UIView,但它只是调整到其父UIView的高度,因此如果具有适当的前导、尾随、顶部和底部约束,则自动标注将起作用。否则布局将不会自动调整其高度。此外,您还需要确保UILabel的行数=0