objective-c - 如何完美计算 UILabel 所需的高度,其中属性字符串包含 HTML 标记

标签 objective-c swift autolayout

我正在解析来自 Google Direction API 的 JSON 响应,它包含 html_instructions。我想在 UILabel 上显示它。但没有得到任何完美的解决方案来计算 UILabel 所需的高度。

html_说明如下:

Merge onto <b>Shankar Sheth Rd</b><div style=\"font-size:0.9em\">Pass by the gas station (on the left)</div>

我尝试过 stackoverflow 上提到的解决方案,例如使用 sizeThatFits()boundingRectWithSize() ,它给了我正确的 html_instructions 高度没有 <div>标签,但当 html_instructions 有 <div> 时它会留下额外的空间标签。

请告诉我如何使用包含 html 标签(如 <div>)的属性文本获取 UILabel 所需的确切高度

最佳答案

我总是使用这个 UILabel 扩展,它也适用于 HTML 标签。没有理由它不应该工作

extension UILabel {

    func sizeForString(string: NSString, constrainedToWidth width: Double) -> CGSize {

        return string.boundingRectWithSize(
            CGSize(
                width: width,
                height: DBL_MAX
            ),
            options: .UsesLineFragmentOrigin,
            attributes: [
                NSFontAttributeName : self.font
            ],
            context: nil).size
    }
}

关于objective-c - 如何完美计算 UILabel 所需的高度,其中属性字符串包含 HTML 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36616880/

相关文章:

ios - 如何计算动态类型的 estimatedRowHeight

swift - 如何在 SwiftUI 上使 LongPressGesture 失败

ios - 当我以编程方式添加一个没有约束的 subview 时会发生什么?

ios - 如何以编程方式添加具有可变高度和布局 ios 的 UILabel

objective-c - cocoa/osx - 阻止 NSTextView 扩展超过其框架尺寸

ios - 更改所有屏幕的 ViewController 后退按钮图像

ios - xCode 6.2 项目不会使用 xCode 6.3 和 Swift 1.2 存档(swiftc 失败,退出代码为 1)

objective-c - Objective C - 调节GDC线程以限制CPU使用

iphone - [UIView beginAnimations :context:] and [UIView animateWithDuration:animations:] 之间的区别

objective-c - UICollectionView 删除按钮