ios UITextView 中的 HTML 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28414999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML Format in UITextView
提问by a2hur
i'm quite new to iOS Development and right now working on an app which receive some kind of JSON Data. But some Backend Experts thought, that it would be better for the User if they just copy the Information straight out of Word and paste it into the information System. So I'm sitting here, trying to make a clickable Link in a UITableView.
我对 iOS 开发很陌生,现在正在开发一个接收某种 JSON 数据的应用程序。但是一些后端专家认为,如果他们直接从Word中复制信息并将其粘贴到信息系统中,对用户来说会更好。所以我坐在这里,试图在 UITableView 中创建一个可点击的链接。
I parse the data from Web and get a String with this format:
我解析来自 Web 的数据并获得具有以下格式的字符串:
Für mehr Informationen klicken sie <a href="http://www.samplelink.com/subpage.php?id=8">here</a>.
I tried already a UILabel, but after some research I use now the often suggested UITextView. In the Attributed Inspector, i set it as an Attributed Text and enabled the Link Detection. Now the text is shown red and is clickable.
我已经尝试过 UILabel,但经过一些研究,我现在使用经常建议的 UITextView。在属性检查器中,我将其设置为属性文本并启用链接检测。现在文本显示为红色并且可以点击。
The Problem now for me is, that the HTML Tags and the correct (German) Character Set is still missing and i got no idea, how to display it in the right way.
我现在的问题是,仍然缺少 HTML 标签和正确的(德语)字符集,我不知道如何以正确的方式显示它。
The shown string is parsed in this way:
显示的字符串以这种方式解析:
func showHTMLString(unformattedString: String) -> NSAttributedString{
var attrStr = NSAttributedString(
data: tmpString.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
return attrStr!
}
If i fill the Textview with attrStr?.string
the Format is shown in the correct way but the link is gone as well.
如果我用attrStr?.string
格式填充 Textview 以正确的方式显示,但链接也不见了。
Any suggestions how to format the shown string in the right way?
任何建议如何以正确的方式格式化显示的字符串?
Thanks in advance AR4G4
提前致谢 AR4G4
回答by Leo Dabus
The problem there is that you have to change the Character Encoding options from NSUnicodeStringEncoding to NSUTF8StringEncoding to load your of your html the proper way. I think you should create a string extension read-only computed property to convert your html code to attributed string:
问题是您必须将字符编码选项从 NSUnicodeStringEncoding 更改为 NSUTF8StringEncoding 才能以正确的方式加载您的 html。我认为您应该创建一个字符串扩展只读计算属性来将您的 html 代码转换为属性字符串:
Xcode 8.3.1 ? Swift 3.1
Xcode 8.3.1 ? 斯威夫特 3.1
extension Data {
var attributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print(error)
}
return nil
}
}
extension String {
var data: Data {
return Data(utf8)
}
}
let htmlStringCode = "Für mehr Informationen klicken sie <a href=\"http://www.samplelink.com/subpage.php?id=8\">here</a>"
htmlStringCode.data.attributedString?.string ?? "" // "Für mehr Informationen klicken sie here"
in your case
在你的情况下
yourTextView.attributedText = htmlStringCode.data.attributedString
回答by fred02138
Check the attributes of your UITextView in IB. In order for the links to work, you must have Selectable
checked.
在 IB 中检查 UITextView 的属性。为了使链接工作,您必须Selectable
检查。
回答by tng
I would recommend displaying HTML in a UIWebView
. It is more robust than using a UITextView
. See Display html text in uitextviewfor more information.
我建议在UIWebView
. 它比使用UITextView
. 有关更多信息,请参阅在 uitextview 中显示 html 文本。
回答by Mannam Brahmam
I used code for Swift 4:
我使用了 Swift 4 的代码:
var descriptionStr : String = String() //Dynamic text
let regex = try! NSRegularExpression(pattern: "<.*?>", options: [.caseInsensitive])
let range = NSRange(location: 0, length: descriptionStr.count)
let htmlLessString: String = regex.stringByReplacingMatches(in: descriptionStr, options: NSRegularExpression.MatchingOptions(), range:range, withTemplate: "")
textViewRef.text = htmlLessString
回答by Rob
Having created your attributed string, you would then set the attributedText
property of the UITextView
to be the NSAttributedString
itself, not the string
property of that attributed string.
创建属性字符串后,您可以将 的attributedText
属性设置UITextView
为NSAttributedString
它本身,而不是该string
属性字符串的属性。
回答by Jeremy Pope
Your versions is pretty close to begin with. As Leonardo Savio Dabus stated you should probably try NSUTF*StringEncoding. The following produces your expected output for me. As he said, you might want to add it to an extension of string, if you are doing this a lot.
你的版本非常接近开始。正如 Leonardo Savio Dabus 所说,您可能应该尝试 NSUTF*StringEncoding。以下内容为我生成了您的预期输出。正如他所说,如果您经常这样做,您可能希望将其添加到字符串的扩展名中。
let theString = "Für mehr Informationen klicken sie <a href=\"http://www.samplelink.com/subpage.php?id=8\">here</a>."
let theAttributedString = NSAttributedString(data: str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil, error: nil)
theTextView.attributedText = atString
回答by Nebojsa Nadj
Another way I used to do this :
我曾经这样做的另一种方式:
var someHtmlString = "Für mehr Informationen klicken sie <a href=\"http://www.samplelink.com/subpage.php?id=8\">here</a>."
let regex = try! NSRegularExpression(pattern: "<.*?>", options: [.CaseInsensitive])
let range = NSRange(location: 0, length: someHtmlString.characters.count)
let htmlLessString: String = regex.stringByReplacingMatchesInString(someHtmlString, options: NSMatchingOptions(), range:range, withTemplate: "")
End result -> htmlLessString is
最终结果 -> htmlLessString 是
"Für mehr Informationen klicken sie here."
回答by Claudia Fitero
I had an app that had a UITextView where I wanted to be able to paste html formatted text from the browser and then save it as a string(containing html formatting) to the database, and then another time retrieve it from the database and show it with the same format as it was first copied from the website. I managed this by making these two extensions:
我有一个具有 UITextView 的应用程序,我希望能够从浏览器粘贴 html 格式的文本,然后将其作为字符串(包含 html 格式)保存到数据库中,然后再从数据库中检索它并显示它格式与最初从网站上复制的格式相同。我通过做这两个扩展来管理这个:
extension String
{
func getAttributedStringFromHTMLString() -> NSAttributedString
{
do {
let attributedString = try NSAttributedString(data: self.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
return attributedString
} catch {
print(error)
return NSAttributedString()
}
}
}
extension NSAttributedString
{
func getHTMLString() -> String
{
var htmlText = "";
let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let htmlData = try self.dataFromRange(NSMakeRange(0, self.length), documentAttributes:documentAttributes)
if let htmlString = String(data:htmlData, encoding:NSUTF8StringEncoding) {
htmlText = htmlString
}
return htmlText
}
catch {
print("error creating HTML from Attributed String")
return ""
}
}
}