Reputation: 707
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 :
And using https://stackoverflow.com/a/58795998/8635708 :
Upvotes: 2
Views: 2084
Reputation: 7232
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)
Upvotes: 0
Reputation: 2355
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
Upvotes: 2