我有一个HTML字符串来自JSON(在REST调用中),HTML需要在UILabel中显示。
以下是我正在使用的代码 -
let htmlText = info.shortDescription
if !(htmlText!.isEmpty) {
var fontAdded: String?
fontAdded = NSString(format: "<html><body><table><tr><td><span style=\"font-family: Lato; font-size: 14; margin: 0; padding: 0;\">%@</span></td></tr></table><br><br><br><br><br></body></html>", htmlText!) as String
if let htmlData = fontAdded!.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true) {
do {
headerView.bodyLabel.attributedText = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],documentAttributes: nil)
} catch let e as NSError {
print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
headerView.bodyLabel.text = info.shortDescription
}
}
}
else {
headerView.bodyLabel.text = info.shortDescription
}
因此,每当我收到一个HTML字符串时,例如,如果它包含Bold / Italics标签,则UILabel会显示HTML字符串中应用的任何样式的文本。
问题: -
HTML字符串中的最后几行被截断。
请注意,没有约束阻止UI显示整个文本。
对于我的fontAdded
,如果我添加更多<br>
个标签,则整个文本都可见,并且没有截断问题。但HTML字符串可以是任何大小,可以随时更改。我不想通过添加** <br>
** s
我还使用NSUTF8StringEncoding
代替NSUnicodeStringEncoding
,但结果没有差异。此外,当我使用NSUTF8StringEncoding
时,我收到的特殊字符无法正常工作。
有人可以帮助解决这个问题吗?
答案 0 :(得分:0)
您可以设置属性字符串的段落样式:
let psSpace = NSMutableParagraphStyle()
psSpace.lineBreakMode = NSLineBreakMode.byWordWrapping
NSAttributedString(data: htmlData,
options: [[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], psSpace],
documentAttributes: nil)
对于 Swift 3 ,是这样的
答案 1 :(得分:0)
谢谢大家......你对约束的评论和意见让我想到了这个方向。我现在通过将底部约束设置为0来实现它。并且,添加了一个高度约束100和“大于或等于”关系:-)并且,当有空HTML时,我将此约束设置为0