查找字符串的宽度(快速)

问题描述 投票:0回答:2

如何根据给定的字体名称和字体大小找到字符串 (CGFloat) 的宽度?

(目标是将 UIView 的宽度设置为足以容纳字符串。)

我有两个字符串:一个“1”重复 36 次,另一个“M”重复 36 次。它们都填充了屏幕的宽度 (359.0)(留出一点边距)。

我正在使用 Courier 16,它是等宽的,所以我希望两个字符串的宽度相等(因为它们实际上确实出现在屏幕上)。

但是,使用https://stackoverflow.com/a/58782429/8635708

  • 带有“1”的字符串的宽度是257.34375
  • 带有“M”的字符串的宽度是492.1875。
  • 第一个是填不满屏幕,另一个是太长了。

并使用 https://stackoverflow.com/a/58795998/8635708 :

  • 每根字符串的宽度是249.640625。
  • 至少在这里,它们是相同的,但该值显然不会填满屏幕。
ios swift font-size
2个回答
1
投票

我认为你可以创建一个标签并调用

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.