我的目标是制作这样的屏幕:
这是我用 StackView 和 Labels 实现的屏幕。 但现在,我想用 UITableView 来做到这一点。我的问题是 Cells 需要是动态的。因为文本可能与其他文本不同。 所以我开始用你的xib文件创建一个UITableViewCell(背景灰色是设计的)
Swift 文件
class CellCreateSaleVC: UITableViewCell {
@IBOutlet weak var lblInfo: UILabel!
@IBOutlet weak var imgClipboard: UIImageView!
@IBOutlet weak var lblNomeCampo: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
带有 UITableView 的 ViewController
class CreateSaleViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableViewMenu: UITableView!
let options : Int = 12
override func viewDidLoad() {
tableViewMenu.dataSource = self
tableViewMenu.delegate = self
tableViewMenu.register(UINib(nibName: "CellCreateSaleVC", bundle: nil), forCellReuseIdentifier: "CellCreateSale")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellCreateSale") as! CellCreateSaleVC
return cell
}
}
最佳答案
对于动态高度TableViewCell,您需要使用self-sizing table view cells ,您必须将 TableView 的 rowHeight 属性设置为 UITableViewAutomaticDimension
。您还必须为 estimatedRowHeight
属性分配一个值。
tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableViewAutomaticDimension
要定义单元格的高度,请向单元格 View 添加从 到 到底部边缘的约束。如果您的 View 具有固有的内容高度,系统将使用这些值。如果没有,您必须向 View 或内容 View 本身添加适当的高度约束。
注意:
Additionally, try to make the estimated row height as accurate as possible. The system calculates items such as the scroll bar heights based on these estimates. The more accurate the estimates, the more seamless the user experience becomes.
引用this使用自动布局动态单元高度的优秀堆栈溢出答案。和 raywendelich.com tutorial在自动调整表格 View 单元格大小上。
关于ios - 如何制作具有动态高度的自定义 UITableViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50780893/