'Last word in UILabel is lost
I have a simple UILabel with some usual constraints.
When I have a small enough text that fits in a line, it renders fine:
text = "Noodles Con Salsa Cremosa De algo"
When I have a big enough text that should flow to the next line, it renders fine again:
text = "Noodles Con Salsa Cremosa De algoalgoalgo"
But strangely, when I have a text of specific size (that barely exceeds one line and must flow to the next line) the last word is lost (It's neither in the first line nor is there any second line!)
text = "Noodles Con Salsa Cremosa De algoalgo"
What is happening to the last word ("algoalgo")? How can I make it work?
Edit: Heres's the code for views and constraints:
// Views:
private let quantityLabel = UILabel()
private let nameLabel = UILabel()
private let descriptionLabel = UILabel()
private let priceLabel = UILabel()
private let infoStackView = UIStackView()
//View setup:
self.addSubview(self.quantityLabel)
self.addSubview(self.infoStackView)
self.addSubview(self.priceLabel)
self.infoStackView.addArrangedSubviews([
self.nameLabel,
self.descriptionLabel])
self.nameLabel.numberOfLines = .zero
self.descriptionLabel.numberOfLines = .zero
self.infoStackView.axis = .vertical
self.infoStackView.spacing = 4.0
// Constraints:
self.quantityLabel.setContentHuggingPriority(.required, for: .horizontal)
self.quantityLabel.snp.makeConstraints { make in
make.leading.equalToSuperview().inset(16.0)
make.top.equalToSuperview().inset(10.0)
}
self.infoStackView.snp.makeConstraints { make in
self.bottomPadding = make.bottom.equalToSuperview().inset(Constants.customPadding).constraint
make.top.equalToSuperview().inset(10)
make.leading.equalTo(self.quantityLabel.snp.trailing).offset(8.0)
}
self.priceLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
self.priceLabel.snp.makeConstraints { make in
make.leading.equalTo(self.infoStackView.snp.trailing).offset(8.0)
make.top.equalToSuperview().inset(10.0)
make.trailing.equalToSuperview().inset(16.0)
}
Solution 1:[1]
I still don't understand what was going on, but it got fixed by setting hugging and content compression priorities to the views at left and right:
quantityLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
nameLabel.setContentCompressionResistancePriority(.required, for: .vertical)
priceLabel.setContentHuggingPriority(.required, for: .horizontal)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |



