如何根据给定的字体名称和字体大小找到字符串 (CGFloat) 的宽度?
(目标是将 UIView 的宽度设置为足以容纳字符串。)
我有两个字符串:一个“1”重复 36 次,另一个“M”重复 36 次。它们都填充了屏幕的宽度 (359.0)(留出一点边距)。
我正在使用 Courier 16,它是等宽的,所以我希望两个字符串的宽度相等(因为它们实际上确实出现在屏幕上)。
但是,使用https://stackoverflow.com/a/58782429/8635708:
并使用 https://stackoverflow.com/a/58795998/8635708 :
我认为你可以创建一个标签并调用
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
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)