Как сделать высоту ячейки в зависимости от содержимого лейблов через код (swift)?
Подскажите, как сделать высоту ячейки в зависимости от содержимого лейблов через код? (приложение без storyboard). Я использую следующие 2 класса, высота лейблов меняется, но высота ячеек остается фиксированной и весь текст не помещается (высота ячейки не динамическая).
import UIKit
class TestViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
lazy var tableViewTest = UITableView()
private let identifire = "CellTest"
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
createTable()
}
private func createTable() {
self.tableViewTest = UITableView(frame: view.bounds, style: .grouped)
tableViewTest.register(TestTableViewCell.self, forCellReuseIdentifier: identifire)
self.tableViewTest.delegate = self
self.tableViewTest.dataSource = self
tableViewTest.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableViewTest.separatorInset.left = 10
tableViewTest.separatorInset.right = 10
view.addSubview(tableViewTest)
tableViewTest.estimatedRowHeight = 50
tableViewTest.rowHeight = UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifire, for: indexPath) as! TestTableViewCell
cell.test1Label.text = "Очень длинный текст, Очень длинный текст, Очень длинный текст, Очень длинный текст"
cell.test2Label.text = "Очень длинный текст"
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
}
Класс для cell:
class TestTableViewCell: UITableViewCell {
let test1Label = UILabel()
let test2Label = UILabel()
override func layoutSubviews() {
super.layoutSubviews()
test1Label.frame = CGRect(x: 30, y: 5, width: UIScreen.main.bounds.width - 80, height: 50)
test1Label.numberOfLines = 0
test1Label.sizeToFit()
test2Label.frame = CGRect(x: 30, y: test1Label.frame.height + 10, width: UIScreen.main.bounds.width - 80, height: 50)
test2Label.numberOfLines = 0
test2Label.sizeToFit()
addSubview(test1Label)
addSubview(test2Label)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}