I want to achieve following UI:
This UI contains label (which is bold on top), stackview (inside blue rectangle), view (gray line) and two labels below of line.
As you see, I have separate view inside stackview. Here is how its constraints are set:
titleLabel.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(16)
make.top.equalToSuperview()
make.bottom.equalToSuperview()
}
priceLabel.snp.makeConstraints { make in
make.trailing.equalToSuperview().offset(-16)
make.top.equalTo(titleLabel.snp.top)
make.leading.equalTo(titleLabel.snp.trailing).offset(16)
}
My goal is to align top of the titleLabel to top of the priceLabel. It seems everything is working, but here is the screenshot of this UI with different text:
As you see, my stackview doesn't give space for bold label. I don't want it to happen. This UI is shown inside bottom sheet with intrinsic layout. I think the problem is that my priceLabel doesn't have bottom constraint. Let's try to give it:
priceLabel.snp.makeConstraints { make in
make.trailing.equalToSuperview().offset(-16)
make.top.equalTo(titleLabel.snp.top)
make.leading.equalTo(titleLabel.snp.trailing).offset(16)
make.bottom.equalToSuperview()
}
Constraints of titleLabel wasn't changed. Here is the result:
It seems everything is ok, but my first titleLabel is too small, even it has numberOfLines set to 0. The another problem is that my priceLabel's top is not aligned with titleLabel's top. I don't want it to happen.
After that, I remembered that UIStackView in UIKit has firstBaseline alignment. Then, I decided to put titleLabel and priceLabel inside horizontal stackview with firstBaseline alignment and fill distribution:
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.distribution = .fill
stackView.alignment = .firstBaseline
stackView.axis = .horizontal
stackView.spacing = 16
return stackView
}()
private func setup() {
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(priceLabel)
addSubview(stackView)
stackView.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(16)
make.trailing.equalToSuperview().offset(-16)
make.bottom.top.equalToSuperview()
}
}
And here is the result:
It is totally ruined. The space between my bold label and stackview is too big. Possibly, the reason for that is bold label's hugging priority.
Final words
As you see, problem is in alignment of labels inside stackview. There are dozens of ways of aligning top of uilabels but all of them give different results. I don't know why. It seems that I don't know something from Auto Layout. So, how to achieve the first screenshot's result?



