2

How do I find the width of a string (CGFloat) given the font name and font size?

(The goal is to set the width of a UIView to be just wide enough to hold the string.)

I have two strings: one with "1" repeated 36 times, the other with "M" repeated 36 times. These both fill the width (359.0) of the screen (give or take a little for margins).

I am using using Courier 16, which is monospaced, so I expect the width of both strings to be equal (as they in fact do appear on the screen).

However, using https://stackoverflow.com/a/58782429/8635708 :

  • the width of the string with the "1"s is 257.34375
  • the width of the string with the "M"s is 492.1875.
  • The first is does not fill the screen, the other is way too long.

And using https://stackoverflow.com/a/58795998/8635708 :

  • the width of each string is 249.640625.
  • At least here, they are the same, but that value clearly does not fill the screen.
1

2 Answers 2

2

I think you could create a label and call label.sizeToFit():

let label = UILabel()
label.font = UIFont.init(name: "Courier", size: 16)
label.text = "mmmmmmmmmmmmmmmm"//"1111111111111111"
label.sizeToFit()
print("Width: \(label.frame.size.width)") //153.66666666666666 -> For both strings
Sign up to request clarification or add additional context in comments.

2 Comments

That would be great for a label, but I want to set the width of a UIView to contain the largest of a number of strings. I tried sizeToFit() with the UIView, but it doesn't work.
Actually, sizeToFit() does work! But only if the UIView's width is already larger than the longest string. It only adjusts down, but not up. Not sure why...
0
let attributedString = NSAttributedString(string: YOUR_STRING, attributes: [NSAttributedString.Key.font: YOUR_FONT])
let line = CTLineCreateWithAttributedString(attributedString)
let lineBounds = CTLineGetBoundsWithOptions(line, .useGlyphPathBounds)
return CGFloat(lineBounds.width)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.