1

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.
Greg
  • 667
  • 8
  • 19

1 Answers1

1

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
finebel
  • 2,227
  • 1
  • 9
  • 20
  • 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. – Greg Aug 19 '20 at 20:08
  • 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... – Greg Aug 19 '20 at 20:34