使用 HTML 数据调整 UILabel 的大小

Resizing UILabel with HTML data

我创建了一个 UILabel 并将其字体大小与搜索栏同步,并将我的 html 格式化文本加载到 UILabel 上。不幸的是,如果我使用搜索栏更改 UILabel 的字体大小,该格式将被删除。

我使用了来自 garie 的这种方法,这是从另一个线程回答的

private func getHtmlLabel(text: String) -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.attributedString = stringFromHtml(string: text)
    return label
}

private func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                             documentAttributes: nil)
            return str
        }
    } catch {
    }
    return nil
}

Link:

有什么方法可以用来保留我的 html 格式化文本吗?

编辑#1: 这就是我调整 UILabel 大小的方式。

@IBOutlet weak var textLabel: UILabel!
@IBAction func resizeText(_ sender: UISlider) {
    textLabel.font = UIFont.systemFont(ofSize: CGFloat(sender.value) * 20.0)
}

我传递到我的 UILabel 的 HTML 数据:

<html><body><b>hello world</b></body></html>

这是 UILabel 上格式化的 HTML 数据:

调整 UILabel 的大小后,它失去了格式:

编辑#2:

尝试了 Milan 的回答,但遇到错误。 NSAttributedStringKey

中未解析的标识符

这是我的代码:

import UIKit

class GalleryViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        textLabel.attributedText = stringFromHtml()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBOutlet weak var textLabel: UILabel!
    @IBAction func resizeText(_ sender: UISlider) {
        if let attributedText = textLabel.attributedText {
            let newAttributedText = NSMutableAttributedString(attributedString: attributedText)
            newAttributedText.setFontSize(newSize: CGFloat(sender.value) * 20.0)
            textLabel.attributedText = newAttributedText
        }
    }


    private func stringFromHtml() -> NSAttributedString? {
        do {
            let string = "<html><body><b>hello world</b></body></html>"
            let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
            if let d = data {
                let str = try NSAttributedString(data: d,
                                                 options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                                 documentAttributes: nil)
                return str
            }
        } catch {
        }
        return nil
    }
}

extension NSMutableAttributedString {
    func setFontSize(newSize: CGFloat) {
        beginEditing()
        self.enumerateAttribute(NSAttributedStringKey.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
            if let f = value as? UIFont {
                let newFont = f.withSize(newSize)
                removeAttribute(NSAttributedStringKey.font, range: range)
                addAttribute(NSAttributedStringKey.font, value: newFont, range: range)
            }
        }
        endEditing()
    }
}

尝试使用 UserDefaults 保存从第二个函数返回的 NSAttributedString:

1- 将属性文本保存在变量中

let attributedText = stringFromHtml(string: String)

2- 将其保存在 UserDefaults

UserDefaults.standard.set(attributedText, forKey: "attributedText")

为了检索它,您可以使用这种格式来安全地解包值:

if let text = UserDefaults.standard.object(forKey: "attributedText") as? NSAttributedString {
   label.attributedString = text
}

直接设置字体会弄乱您的属性文本。您必须在属性文本上设置字体大小:

@IBAction func resizeText(_ sender: UISlider) {
    if let attributedText = textLabel.attributedText {
        let newAttributedText = NSMutableAttributedString(attributedString: attributedText)
        newAttributedText.setFontSize(newSize: CGFloat(sender.value) * 20.0)
        textLabel.attributedText = newAttributedText
    }
}

为此,您需要在 NSMutableAttributedString 上进行以下扩展:

extension NSMutableAttributedString {
    func setFontSize(newSize: CGFloat) {
        beginEditing()
        self.enumerateAttribute(NSAttributedStringKey.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
            if let f = value as? UIFont {
                let newFont = f.withSize(newSize)
                removeAttribute(NSAttributedStringKey.font, range: range)
                addAttribute(NSAttributedStringKey.font, value: newFont, range: range)
            }
        }
        endEditing()
    }
}