@JaubSanestrzik - много-много-много причин использовать код вместо (или вместе с ним) раскадровок / Интерфейсного Разработчика. Проблема в этом случае, похоже, не имеет ничего общего с неправильными ограничениями.
Я прочитал несколько ответов отИспользование Auto Layout в UITableView для динамического размещения ячеек и переменной высоты строк
И следовал их предложениям, но это не работает.
Настройка для воспроизведения:Если вы копируете / вставляетеMyTableViewCell
а такжеViewController
фрагменты: тогда вы можете воспроизвести проблему.
Я подкласс MyTableViewCell и добавил свой собственный ярлык.
import UIKit
class MyTableViewCell: UITableViewCell {
lazy var customLabel : UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.numberOfLines = 0
return lbl
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupLayout()
}
private func setupLayout(){
contentView.addSubview(customLabel)
let top = customLabel.topAnchor.constraint(equalTo: contentView.topAnchor)
let bottom = customLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
let leadingFromImage = customLabel.leadingAnchor.constraint(equalTo: imageView!.trailingAnchor, constant: 5)
let trailing = customLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
NSLayoutConstraint.activate([top, bottom, leadingFromImage, trailing])
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
}
ПоследующийViewController
содержит мой просмотр таблицы:
import UIKit
class ViewController: UIViewController {
var datasource = ["It would have been a great day had Manchester United Lost its \n game. Anyhow I hope tomorrow Arsenal will win the game"]
lazy var tableView : UITableView = {
let table = UITableView()
table.delegate = self
table.dataSource = self
table.translatesAutoresizingMaskIntoConstraints = false
table.estimatedRowHeight = 100
table.rowHeight = UITableViewAutomaticDimension
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.pinToAllEdges(of: view)
tableView.register(MyTableViewCell.self, forCellReuseIdentifier: "id")
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id", for: indexPath) as! MyTableViewCell
cell.customLabel.text = datasource[indexPath.row]
logInfo(of: cell)
cell.accessoryType = .detailDisclosureButton
cell.imageView?.image = UIImage(named: "honey")
cell.layoutSubviews()
cell.customLabel.preferredMaxLayoutWidth = tableView.bounds.width
logInfo(of: cell)
print("---------")
return cell
}
private func logInfo(of cell: MyTableViewCell){
print("boundsWidth: \(cell.contentView.bounds.width) | maxLayoutWidth: \(cell.contentView.bounds.width - 44 - 15 - 5) | systemLayoutSizeFitting : \(cell.customLabel.systemLayoutSizeFitting(UILayoutFittingCompressedSize))")
}
}
extension UIView{
func pinToAllEdges(of view: UIView){
let leading = leadingAnchor.constraint(equalTo: view.leadingAnchor)
let top = topAnchor.constraint(equalTo: view.topAnchor)
let trailing = trailingAnchor.constraint(equalTo: view.trailingAnchor)
let bottom = bottomAnchor.constraint(equalTo: view.bottomAnchor)
NSLayoutConstraint.activate([leading, top, trailing, bottom])
}
}
Ссылка длямилый образ Я использовал. Я установил его размер44 * 44
Моя главная проблема внутриcellForRowAtIndex
:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id", for: indexPath) as! MyTableViewCell
cell.customLabel.text = datasource[indexPath.row]
logInfo(of: cell)
cell.accessoryType = .detailDisclosureButton
cell.imageView?.image = UIImage(named: "honey")
cell.layoutSubviews()
cell.customLabel.preferredMaxLayoutWidth = cell.contentView.bounds.width
logInfo(of: cell)
print("---------")
return cell
}
Вопросов:
По какой-либо причине значение присваивается:
cell.customLabel.preferredMaxLayoutWidth
не кажется правильным
Q1: Почему это?
Q2: Я регистрирую привязку contentView до и после вызоваcell.layoutSubviews
и он переключается с320
в260
но затем, в конце концов, в viewDebugger это выглядит как308
!!!
Почему границы contenView снова меняются ?!
Я удалил некоторые другие скриншоты из вопроса. Они были в основном беспорядочные, но, возможно, стоит посмотреть Вы можете взглянуть на историю изменений.