Неправильная высота с автоматическим определением размеров таблицы - PullRequest
0 голосов
/ 06 ноября 2018

Сценарий

Я использую опцию automaticDimension в UITableView. Я бы хотел, чтобы в моей ячейке была одна UILabel, которая сама по себе подходит для текста.

Настройка

Autolayout config Здесь вы можете увидеть, как я настраиваю метку. Края равны полям contentView.

Задача

Высота телефона составляет 37,0, когда текст умещается в одну строку. 44,0 должно быть минимумом.

Вопрос

Как мне настроить макет, чтобы поддерживать минимальную высоту ячейки 44,0 (высота по умолчанию, подгонка к другим ячейкам)?

Edit:

Использование встроенного «базового» TableViewCell с numberOfLines = 0 представляется наиболее простым и лучшим решением! Предложено eddwinpaz. Спасибо всем.

Ответы [ 2 ]

0 голосов
/ 06 ноября 2018

Вам нужно использовать numberOfLine = 0, если вы просто работаете с Single UILabel. Else. Вам нужно использовать ограничения.

import UIKit

class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 5
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

    return cell
}

}

В случае, если вам нужно использовать пользовательский UILabel, как ваш случай.

class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(CustomCell.self, forCellReuseIdentifier: "reuseIdentifier")
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 5
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CustomCell
    cell.myLabel.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

    return cell
}

 }

class CustomCel: UITableViewCell {

let myLabel: UILabel = {
   let label = UILabel()
    label.numberOfLines = 0
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

func setupViews(){
    addSubview(myLabel)

    myLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    myLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
    myLabel.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
    myLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

 }
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
0 голосов
/ 06 ноября 2018

Измените верхний якорь с constraint(equalTo:) на greaterThanOrEqualTo:, а нижний на lessThanOrEqualTo:. Затем сделайте ярлык по центру оси Y.

Тогда вы должны установить cell. heightAnchor.constraint(greaterThanOrEqualToConstant: 44)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...