【问题标题】:Swift : boundingRectWithSize return wrong height for a multiline labelSwift:boundingRectWithSize 为多行标签返回错误的高度
【发布时间】:2016-08-21 16:09:19
【问题描述】:

我正在使用 String 类的扩展来获取在多行标签中显示我的字符串所需的高度。

extension String {
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: CGFloat.max)

        let option = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)

        let boundingBox = self.boundingRectWithSize(constraintRect, options: option, attributes: [NSFontAttributeName: font], context: nil)
        print("ex width \(boundingBox.width)")
        print("ex height \(boundingBox.height)")
        return boundingBox.height
    }
}

我打电话给heightForRowAtIndexPath

let myRandomString = "My baby looks like she's ashamed and wants to apologise for something bad she did."
let labelWidth = UIScreen.mainScreen().bounds.width-16
let labelHeight = myRandomString.heightWithConstrainedWidth(labelWidth,font: UIFont.boldSystemFontOfSize(17))

我得到:

ex width 359.0
ex height 40.57421875

但是当我使用 xcode 的视图调试选项时,我得到了这个:

这就是我的 UILabel 的设置方式:

如您所见,我的宽度是正确的(我是强制的),但我的高度不正确,我不知道为什么。

感谢和问候, 埃里克

【问题讨论】:

    标签: ios swift string uilabel


    【解决方案1】:

    对于多行仅使用.UsesLineFragmentOrigin

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      相关资源
      最近更新 更多