gpt4 book ai didi

swift - 在 textView 的 HTML 属性文本上通过 CSS 填充不起作用

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:44 24 4
gpt4 key购买 nike

我正在渲染一个带有 HTML 内容的 TextView 。我采用了一些“div”标签并在其上应用了一些 CSS。我在使用 CSS 类在“div”上应用填充时遇到问题,该类在 textview 上呈现后未反射(reflect)在 div 上。我使用以下方法将 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;
}

最佳答案

问题是 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
}

这是将文本转换为 NSAttributedStringString 扩展。

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)

关于swift - 在 textView 的 HTML 属性文本上通过 CSS 填充不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39040452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com