我正在使用HTML内容呈现textview。我已经采取了一些" div"标签并在它们上应用了一些CSS。我在" div"上应用填充时遇到了一个问题。使用在textview上渲染后不反映div的CSS类。我使用以下方法将HTML内容字符串转换为属性字符串。
if let htmlData = htmlContent.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true) {
do {
return try NSMutableAttributedString(
data: htmlData,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
}
catch let error as NSError {
printDebuggingMode("Couldn't translate \(htmlContent): \(error.localizedDescription) ")
}
}
我希望在textView的图像中实现下面附带的内容。
.padding {
padding-left: 20px;
}
答案 0 :(得分:0)
问题是UITextView
不支持HTML内容中的 padding 属性。考虑到这一点,你有两个选择:
一方面,根据回复中的建议使用UIWebView
。您将拥有与UITextView
相同的功能,但您必须使用以下内容计算文字的高度:
此方法返回高度而不考虑UITextView
的插入内容,您需要稍后添加它们。
func heightForText(text: String?, width: CGFloat) -> CGFloat {
//Get attributed text from string
let attributedText = text?.toHtmlTextWithAttributes()
if let attributedText = attributedText {
let rect = attributedText.boundingRectWithSize(
CGSizeMake(width, CGFloat.max),
options: [.UsesLineFragmentOrigin, .UsesFontLeading],
context: nil)
return rect.height
}
//Return any default height
return 100
}
以下是String
扩展程序,可将文本转换为NSAttributedString
。
extension String {
public func toHtmlTextWithAttributes() -> NSAttributedString? {
let encodedData = self.dataUsingEncoding(NSUTF8StringEncoding)
if let data = encodedData {
let paragrahpStyle = NSMutableParagraphStyle()
paragrahpStyle.lineBreakMode = .ByWordWrapping
let attributes: [String: NSObject] = [
NSParagraphStyleAttributeName: paragrahpStyle,
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
return try! NSAttributedString(data: data, options: attributes, documentAttributes: nil)
}
return nil
}
}
不建议使用UITableViewAutomaticDimension
,因为在相当大的列表中可能会导致性能问题。
另一方面,如果您需要一定使用UITextView
,您可以解析html,提取标题和段落,并以两个独立的UITextView
显示它们。通过这种方式,您可以像这样调整第二个UITextView
的插图:
textView.textContainerInset = UIEdgeInsetsMake(0, 20, 0, 0)