Format HTML w UITextView
Jestem całkiem nowy w rozwoju iOS, a teraz pracuję nad aplikacją, która odbiera jakieś dane JSON. Ale niektórzy eksperci Backend myśleli, że byłoby lepiej dla użytkownika, jeśli po prostu skopiować informacje prosto z programu Word i wkleić go do systemu informacyjnego. Więc siedzę tutaj, próbując zrobić klikalny Link w widoku UITableView.
Analizuję dane z Web i otrzymuję ciąg znaków o takim formacie:
Für mehr Informationen klicken sie <a href="http://www.samplelink.com/subpage.php?id=8">here</a>.
Próbowałem już UILabel, ale po kilku badaniach używam teraz często sugerowane UITextView. W przypisanym Inspektorze ustawiłem go jako przypisany tekst i włączyłem wykrywanie łącza. Teraz tekst jest wyświetlany na czerwono i można go kliknąć.
Problem jest teraz dla mnie, że znaczniki HTML i poprawny (niemiecki) zestaw znaków nadal brakuje i nie mam pojęcia, jak wyświetlić go w odpowiedni sposób.
Pokazany łańcuch jest przetwarzany w ten sposób:
func showHTMLString(unformattedString: String) -> NSAttributedString{
var attrStr = NSAttributedString(
data: tmpString.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
return attrStr!
}
Jeśli wypełnię Textview attrStr?.string
Format jest wyświetlany w prawidłowy sposób, ale link zniknął.
Jakieś sugestie jak poprawnie sformatować wyświetlany ciąg znaków?
Z góry dzięki AR4G48 answers
Problem polega na tym, że musisz zmienić opcje kodowania znaków z NSUnicodeStringEncoding na NSUTF8StringEncoding, aby załadować swój html we właściwy sposób. Myślę, że powinieneś utworzyć właściwość string extension Read-only computed, aby przekonwertować kod html na przypisany ciąg znaków:
Xcode 8.3.1 * Swift 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"
W Twoim przypadku
yourTextView.attributedText = htmlStringCode.data.attributedString
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-12 00:16:18
Sprawdź atrybuty UITextView w IB. Aby linki działały, musisz sprawdzić Selectable
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-09 18:02:10
Polecam wyświetlanie HTML w UIWebView
. Jest bardziej wytrzymały niż użycie UITextView
. Zobacz Wyświetl tekst html w uitextview Aby uzyskać więcej informacji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:50
Użyłem kodu do 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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-01 10:17:05
Po utworzeniu przypisanego ciągu, ustawisz attributedText
Właściwość UITextView
jako samą NSAttributedString
, a nie string
właściwość tego przypisanego ciągu.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-09 17:40:48
Twoje wersje są dość blisko. Jak stwierdził Leonardo Savio Dabus, prawdopodobnie powinieneś wypróbować Nsutf * StringEncoding. Poniżej przedstawiamy oczekiwaną dla mnie produkcję. Jak powiedział, możesz dodać go do rozszerzenia ciągu, jeśli robisz to często.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-09 20:55:04
Inny sposób, w jaki to robiłem:
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: "")
Wynik końcowy - > htmlLessString jest
"Für mehr Informationen klicken sie here."
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-06 22:40:31
Miałem aplikację, która miała UITextView gdzie chciałem być w stanie wkleić HTML sformatowany tekst z przeglądarki, a następnie zapisać go jako ciąg znaków (zawierające formatowanie html) do bazy danych, a następnie innym razem pobrać go z bazy danych i pokazać go w tym samym formacie, jak to było najpierw skopiowane ze strony internetowej. Udało mi się to poprzez zrobienie tych dwóch rozszerzeń:
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 ""
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-12 14:33:47