【问题标题】:how much pixels dose a character takes in iOS?一个角色在 iOS 中需要多少像素?
【发布时间】: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。 我不明白。 请给我一些提示。 感谢您的关注。 ????

通过使用sizeWithAttributesboundingRectWithSize(_: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/…

标签: ios swift uilabel


【解决方案1】:

根据字符、字体和字体大小,每个字符占用不同的空间。

因此,您可以在运行时使用boundingRectWithSize(_:options:context:) 来预测字符串的大小,然后根据您的要求采取措施。

【讨论】:

  • 谢谢!我知道它现在是如何工作的。但我最初的目的是将 10 个字符放在一行中。代码应该计算字符之间的空间,并且所有的空间都是相同的大小。你能给我一些建议吗?
  • 你打算显示多少这样的行?似乎您需要使用集合视图而不是标签。每个字符都在集合的一个单元格内iw
猜你喜欢
  • 1970-01-01
  • 2011-02-13
  • 2023-04-01
  • 2017-05-06
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
相关资源
最近更新 更多