Como obter corretamente o conteúdo do tableViewCell'sViewView bound size?
Li várias respostas deUsar o layout automático no UITableView para layouts de células dinâmicos e alturas de linhas variáveis
E seguiu as sugestões deles, mas não está funcionand
Configuração para reproduzir:Se você copiar / colar oMyTableViewCell
eViewController
snippets: então você pode reproduzir o problem
Subclassifiquei MyTableViewCell e adicionei meu próprio rótul
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()
}
}
Os seguintesViewController
contém minha tableview:
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])
}
}
Link parahoney image Eu usei. Eu configurei o tamanho para44 * 44
Meu grande problema está dentrocellForRowAtIndex
:
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
}
Questões
Por qualquer motivo, o valor atribuído a:
cell.customLabel.preferredMaxLayoutWidth
parece não estar certo.
Q1: Por que é que
Q2: Estou registrando o limite do contentView antes e depois de ligar paracell.layoutSubviews
e muda de320
para260
mas, eventualmente, no viewDebugger, ele aparece como308
!!!
Por que os limites do contenView estão mudando novamente?!
Eu removi outras capturas de tela da pergunta. Eles eram principalmente desorganizados, mas talvez valessem a pena procurar. Você pode dar uma olhada no histórico de revisões.