【发布时间】:2016-12-11 06:08:58
【问题描述】:
我查看了几个教程,这些教程展示了如何设置动态单元格高度,但所有这些教程都仅在您通过设置适当的约束并使用 UITableViewAutomaticDimension 来使用动态单元格时才显示。但是,我想对静态单元格执行此操作。
我的应用程序中有一个表格视图控制器,其中包含几个单元格,这些单元格显示一个带有披露指示器的类别,其中有一个标题和一个描述,描述文本的大小会有所不同。因此,我希望单元格的高度根据描述文本的大小是动态的。
我使用静态单元格而不是动态单元格的原因是因为在类别单元格上方我有一些单元格具有一些我只能通过使用静态单元格和情节提要获得的设计。
我正在使用iOS9、Xcode 7.3 和Swift 2.2
更新
表格视图控制器代码
import UIKit
class CategoriesTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}
}
更新 2
根据下面接受的答案,我将以下两种方法添加到我的表格视图控制器中,并删除了我在 viewDidLoad() 中的 2 行。这是为我做的!请记住,我必须确保每个单元格中的所有标签都使用顶部、底部、前导和尾随约束。此外,每个标签的行数必须设置为 0。
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
【问题讨论】: