【发布时间】:2016-06-14 11:49:02
【问题描述】:
我正在尝试在 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 个字符放在一行中。代码应该计算字符之间的空间,并且所有的空间都是相同的大小。你能给我一些建议吗?
This is what I want to make
【问题讨论】:
-
所以你要计算字符占用的宽度?
-
I turned off the Size Class and Auto Layout for convenience-- 重新打开它们。如果没有其他原因,除了不必有一个巨大的查找表来配对字体+大小到高度(然后仍然必须猜测宽度)的便利。 -
答案是“这取决于字符”。 iOS 使用比例字体,因此像“I”这样的字母比像“W”这样的字母占用的空间要少得多。你可以使用
sizeWithAttributes- stackoverflow.com/questions/24141610/…