我已经看过几个教程,这些教程展示了如何设置动态单元高度,但所有这些教程仅在您通过设置适当的约束并使用动态单元来使用动态单元时才显示UITableViewAutomaticDimension
。但是,我想对静态单元格执行此操作。
我的应用程序中有一个表视图控制器,其中包含多个单元格,这些单元格显示带有公开指示符的类别,其中有标题,然后有说明,说明文本的大小各不相同。因此,我希望单元格的高度根据描述文本的大小是动态的。
我使用静态单元而不是动态单元的原因是因为在类别单元之上,我有一些单元具有一些只能通过使用静态单元和故事板才能获得的设计。
我在用iOS9
, Xcode 7.3
and Swift 2.2
UPDATE
表视图控制器代码
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
}
}
UPDATE 2
根据下面接受的答案,我将下面的两种方法添加到我的表视图控制器中,并删除了 viewDidLoad() 中的两行。这为我做到了!请记住,我必须确保每个单元格中的所有标签都使用顶部、底部、前导和尾随约束。此外,每个标签的行数必须设置为 0。
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}