Steven James
Steven James

Reputation: 81

UILabel's content size is not equal to the width anchor

I've constrained my UILabel to constant width using NSLayoutConstraint and widthAnchor, the problem is, the contentSize of the UILabel is not equal to the widthAnchor and in some cases is greater than what I specified.

Why is that the case? P.S. I'm a beginner to iOS Development, apologies if the answer is obvious.

Edit: The UILabel's width was constrained to a decimal point value, which according to one user on another forum caused the UILabel to round up to the next 0.5 multiple, this caused the whole system to break. The work around for me was ceil() the width of my UILabel. Thanks to everyone who helped.

Upvotes: 0

Views: 396

Answers (2)

Steven James
Steven James

Reputation: 81

The UILabel's width was constrained to a decimal point value, which according to one user on another forum caused the UILabel to round up to the next 0.5 multiple, this caused the whole system to break. The work around for me was ceil() the width of my UILabel. Thanks to everyone who helped.

Upvotes: 0

Mohmmad S
Mohmmad S

Reputation: 5098

You can use the compression resistance priority here,

  1. Set a lower priority for WidthAnchor
  2. Set content compression resistance priority to 1000 for example ( higher than width anchor )

check code below.

label.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)

This article might be helpful in your case.

Upvotes: 1

Related Questions