Home > Software design >  UILabel's content size is not equal to the width anchor
UILabel's content size is not equal to the width anchor

Time:09-21

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related