Я подготовил UITableViewCell в nib-файле со всеми ограничениями сверху вниз. Расчет высоты строки в табличном представлении, кажется, работает.
Но если я хочу активировать / деактивировать некоторые другие ограничения в ячейке на основе некоторого условия данных строки, то у меня есть проблема, потому что кажется, что высота не рассчитывается тогда. В чем проблема? В следующем примере TableRowDM.hidden
означает, должны ли субтитры быть скрытыми или нет. Я скрываю эту UILabel, активируя не активированное ограничение (высота с константой = 0) и устанавливая вертикальный разрыв между titleLabel и subtitleLabel равным 0.
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 изменяется, высота корректируется в соответствии с текстом внутри этих UIViews, но когда я пытаюсь манипулировать с ограничениями, это не работает. Любая помощь? Что я делаю неправильно? CellView - это очень простой вид с такими подпредставлениями
-----------------
|
- titleLabel ----
|
| <- titleToSubtitleGap
|
- subtitleLabel -
|
-----------------