【发布时间】:2018-07-14 08:18:28
【问题描述】:
我创建了一个 UILabel 并将其字体大小与搜索栏同步,并将我的 html 格式文本加载到 UILabel 上。不幸的是,如果我使用 seekbar 更改 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
}
链接:Swift: Display HTML data in a label or textView
有什么方法可以用来保留我的 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:
尝试了米兰的答案,但遇到了错误。 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()
}
}
【问题讨论】:
-
展示如何在标签中调整文本大小
-
添加了调整我的 UILabel 字体大小的代码。
-
试试我的答案..还没测试过,但我们会看到
-
或者使用TextView设置不滚动
标签: html ios swift swift3 uilabel