【发布时间】:2018-11-17 15:58:49
【问题描述】:
我在 nib 文件中准备了 UITableViewCell,所有约束从上到下。在表格视图中计算行高似乎可行。
但是,如果我想根据某些行数据条件激活/停用单元格中的其他一些约束,那么我会遇到问题,因为当时似乎没有计算高度。问题是什么?在以下示例中,TableRowDM.hidden 表示是否隐藏字幕。我通过激活未激活的约束(常量 = 0 的高度)并将 titleLabel 和 subtitleLabel 之间的垂直间隙设置为 0 来隐藏此 UILabel。
struct TableRowDM {
let title: String
let subTitle: String
let hidden: Bool
}
let cellId: String = "CellView"
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
let rowData: [TableRowDM] = [
TableRowDM(title: "Row 1", subTitle: "Short title 1th row", hidden: false),
TableRowDM(title: "Row 2", subTitle: "Short title 2th row", hidden: true),
TableRowDM(title: "Row 3", subTitle: "Very long text in subtitle at 3th row to test text wrapping and growing subtitle height", hidden: false),
TableRowDM(title: "Row 4", subTitle: "Long text in subtitle at 4th row", hidden: false),
TableRowDM(title: "Row 5", subTitle: "Long text in subtitle at 5th row", hidden: true),
TableRowDM(title: "Row 6", subTitle: "Long text in subtitle at 6th row", hidden: false),
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 50
tableView.tableFooterView = UIView(frame: CGRect.zero)
tableView.register(UINib(nibName: cellId, bundle: nil), forCellReuseIdentifier: cellId)
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! CellView
let row: TableRowDM = self.rowData[indexPath.row]
cell.title.text = row.title
cell.subtitle.text = row.subTitle
if row.hidden {
// hide subtitle
cell.subtitleHeight.isActive = true
cell.titleToSubtitleGap.constant = 0
} else {
// show subtitle
cell.subtitleHeight.isActive = false
cell.titleToSubtitleGap.constant = 16
}
cell.setNeedsLayout()
cell.layoutIfNeeded()
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowData.count
}
}
这似乎不起作用,并且 subtitleLabel 没有隐藏并且行高始终相同。当 subtitleLabel 和 titleLabel 的内容发生变化时,高度会调整为这些 UIView 内的文本,但是当我尝试使用约束进行操作时,它就不起作用了。有什么帮助吗?我究竟做错了什么? CellView 是带有此类子视图的非常简单的视图
-----------------
|
- titleLabel ----
|
| <- titleToSubtitleGap
|
- subtitleLabel -
|
-----------------
【问题讨论】:
标签: ios uitableview autolayout uikit