一个字符在 iOS 中占多少像素?
how much pixels dose a character takes in iOS?
我正在尝试在 UILabel 视图上自动布置文本。
文本(例如 "abcdefghij")包含十个字符。我想在一行中显示它。
为方便起见,我关闭了 Size Class 和 Auto Layout,并添加了以下代码来对 UILabel 上的文本进行布局。一行应该是十个字符,UILabel 的宽度等于设备的宽度。
let screenWidth = UIScreen.mainScreen().bounds.width
labelView.frame = CGRect(x: labelView.frame.origin.x, y: labelView.frame.origin.y, width: screenWidth, height: labelView.frame.height)
let string = "abcdefghij"
let stringLength = CGFloat(string.characters.count)
let characterSize = keyboardView.font.pointSize
let characterSpacing = (screenWidth - characterSize * stringLength) / stringLength
let content = NSAttributedString(string: string, attributes: [NSKernAttributeName: characterSpacing])
keyboardView.attributedText = content
结果却变成了这样。 The width of string is not equal to the screen
我认为,这里唯一可能出错的是 pointSize。当我将字体大小设置为 17 时,它等于 13.8。
我不明白。
请给我一些提示。
感谢您的关注。
通过使用sizeWithAttributes
和boundingRectWithSize(_:options:context:)
,我终于明白了它是如何工作的。但我最初的目的是将 10 个字符放在一行中。代码应计算字符之间的 space,并且所有 space 大小相同。你能给我一些建议吗?
This is what I want to make
根据字符、字体和字体大小,每个字符占用不同的space。
因此,您可以使用boundingRectWithSize(_:options:context:)
在运行时预测字符串的大小,然后根据您的要求采取行动。
我正在尝试在 UILabel 视图上自动布置文本。 文本(例如 "abcdefghij")包含十个字符。我想在一行中显示它。 为方便起见,我关闭了 Size Class 和 Auto Layout,并添加了以下代码来对 UILabel 上的文本进行布局。一行应该是十个字符,UILabel 的宽度等于设备的宽度。
let screenWidth = UIScreen.mainScreen().bounds.width
labelView.frame = CGRect(x: labelView.frame.origin.x, y: labelView.frame.origin.y, width: screenWidth, height: labelView.frame.height)
let string = "abcdefghij"
let stringLength = CGFloat(string.characters.count)
let characterSize = keyboardView.font.pointSize
let characterSpacing = (screenWidth - characterSize * stringLength) / stringLength
let content = NSAttributedString(string: string, attributes: [NSKernAttributeName: characterSpacing])
keyboardView.attributedText = content
结果却变成了这样。 The width of string is not equal to the screen
我认为,这里唯一可能出错的是 pointSize。当我将字体大小设置为 17 时,它等于 13.8。 我不明白。 请给我一些提示。 感谢您的关注。
通过使用sizeWithAttributes
和boundingRectWithSize(_:options:context:)
,我终于明白了它是如何工作的。但我最初的目的是将 10 个字符放在一行中。代码应计算字符之间的 space,并且所有 space 大小相同。你能给我一些建议吗?
This is what I want to make
根据字符、字体和字体大小,每个字符占用不同的space。
因此,您可以使用boundingRectWithSize(_:options:context:)
在运行时预测字符串的大小,然后根据您的要求采取行动。