Я пытаюсь сделать это с помощью tableHeaderView. Заголовок содержит titleLabel иdescriptionLabel, расположенные внутри UIStackView. Я также хочу добавить отступы вокруг UIStackView.
Вот упрощенная версия моего CustomHeaderView:
Код: Выделить всё
class CustomHeaderView: UIView {
var padding: UIEdgeInsets = .zero
// MARK: - UI Elements
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var descriptionLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var stackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [titleLabel, descriptionLabel])
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
private func setupView() {
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: topAnchor, constant: padding.top),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding.left),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding.right),
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding.bottom),
])
}
}
Код: Выделить всё
override func viewDidLoad() {
super.viewDidLoad()
let headerView = CustomHeaderView()
headerView.padding = .init(top: 70, left: 23, bottom: 8, right: 23)
tableView.tableHeaderView = headerView
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.updateHeaderViewHeight()
}
Код: Выделить всё
extension UITableView {
func updateHeaderViewHeight() {
guard let headerView = self.tableHeaderView else { return }
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let size = headerView.systemLayoutSizeFitting(CGSize(width: self.bounds.width, height: 0))
if headerView.frame.size.height != size.height {
headerView.frame.size.height = size.height
self.tableHeaderView = headerView
}
}
}
Первое предупреждение:
Код: Выделить всё
(
"",
"",
"",
"",
"",
""
)
Will attempt to recover by breaking constraint
Код: Выделить всё
(
"",
"",
""
)
Will attempt to recover by breaking constraint
Как я могу правильно управлять заполнением и динамически регулировать высоту tableHeaderView, не сталкиваясь с этими предупреждениями автоматического макета?
Подробнее здесь: https://stackoverflow.com/questions/792 ... -in-uitabl
Мобильная версия