0

I have a UITextField that will display floating point values between 0 and 1.0 with 3 digits after the decimal point. So the widest text it will show is something like "0.000". I'd like to set the auto layout width constraint so that the text field always has just enough room to display this value.

The code below is close, but does not work.

let biggestString = "0.000"
let textAttrs = [NSAttributedStringKey.font: myField.font]
let size = (biggestString as NSString).size(withAttributes: textAttrs)
myField.widthAnchor.constraint(equalToConstant: size.width).isActive = true

It ends up displaying "1.0..." I'm guessing this is because a UITextField has some kind of padding around the text, so so I need to set the width to be the string width + the padding. But, I don't see a property from which I can read this padding amount. Is there a way to get it?

Rob N
  • 15,024
  • 17
  • 92
  • 165

1 Answers1

0

Try searching for the 'intrinsicContentSize'. According to the documentation this is what has to be set to indicate to the auto-layout how big the content is.

There was also a more elaborate discussion on how this can actually if the layout settings do not allow the resizing to work, see other question here:

How to increase width of textfield according to typed text?

Peter Branforn
  • 1,679
  • 3
  • 17
  • 29