programing tip

uitextview에 html 텍스트 표시

itbloger 2020. 10. 13. 07:30
반응형

uitextview에 html 텍스트 표시


Textview에서 HTML 텍스트를 어떻게 표시 할 수 있습니까?

예를 들면

string <h1>Krupal testing <span style="font-weight:
bold;">Customer WYWO</span></h1>

텍스트가 굵게 표시되어 textview에 굵은 문자열로 표시되지만 일반 텍스트를 표시하고 싶다고 가정합니다. iPhone SDK에서 가능합니까?


iOS 5에서 UIWebView를 사용하십시오.

iOS 6 이상에서는을 사용할 수 있습니다 . 방법 UITextView.attributedStringhttps://stackoverflow.com/a/20996085참조 하세요 .


도 있습니다 문서화되지 않은 -[UITextView setContentToHTMLString:] 방법. AppStore에 제출하려면 이것을 사용하지 마십시오.


iOS 7 이상에서는 다음 코드 블록을 사용하십시오.

NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p><img src='http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg' width=70 height=100 />";
NSAttributedString *attributedString = [[NSAttributedString alloc]
          initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
               options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
    documentAttributes: nil
                 error: nil
];
textView.attributedText = attributedString;

대한 스위프트 4스위프트 4.2 :

let htmlString = "<html>" +
        "<head>" +
        "<style>" +
        "body {" +
        "background-color: rgb(230, 230, 230);" +
        "font-family: 'Arial';" +
        "text-decoration:none;" +
        "}" +
        "</style>" +
        "</head>" +
        "<body>" +
        "<h1>A title</h1>" +
        "<p>A paragraph</p>" +
        "<b>bold text</b>" +
    "</body></html>"

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]

let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)

textView.attributedText = attributedString

대한 스위프트 3 :

let htmlString = "<html>" +
"<head>" +
    "<style>" +
        "body {" +
            "background-color: rgb(230, 230, 230);" +
            "font-family: 'Arial';" +
            "text-decoration:none;" +
        "}" +
    "</style>" +
"</head>" +
"<body>" +
    "<h1>A title</h1>" +
    "<p>A paragraph</p>" +
    "<b>bold text</b>" +
"</body></html>"

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

textView.attributedText = attributedString

BHUPI의 대답은 정확하지만 UILabel 또는 UITextView의 사용자 정의 글꼴을 HTML 콘텐츠와 결합하려면 html을 약간 수정해야합니다.

NSString *htmlString = @"<b>Bold</b><br><i>Italic</i><p> <del>Deleted</del><p>List<ul><li>Coffee</li><li type='square'>Tea</li></ul><br><a href='URL'>Link </a>";

htmlString = [htmlString stringByAppendingString:@"<style>body{font-family:'YOUR_FONT_HERE'; font-size:'SIZE';}</style>"];
/*Example:

 htmlString = [htmlString stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>",_myLabel.font.fontName,_myLabel.font.pointSize]];
*/
 NSAttributedString *attributedString = [[NSAttributedString alloc]
                      initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
                           options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                documentAttributes: nil
                             error: nil
            ];
textView.attributedText = attributedString;

아래 그림에서 차이점을 볼 수 있습니다. enter image description here


You can have a look the OHAttributedLabel classes, I used these to overcome this kind of problem with my textField. In this they have overridden the drawRect method to obtain the required style.

https://github.com/AliSoftware/OHAttributedLabel


My first response was made before iOS 7 introduced explicit support for displaying attributed strings in common controls. You may now set attributedText of UITextView to an NSAttributedString created from HTML content using:

-(id)initWithData:(NSData *)data options:(NSDictionary *)options documentAttributes:(NSDictionary **)dict error:(NSError **)error 

- initWithData:options:documentAttributes:error: (Apple Doc)

Original answer, preserved for history:

Unless you use a UIWebView, your solution will rely directly on CoreText. As ElanthiraiyanS points out, some open source projects have emerged to simplify rich text rendering. I would recommend NSAttributedString-Additions-For-HTML (Edit: the project has been supplanted DTCoreText), which features classes to generate and display attributed strings from HTML.


Answer has fitted to me that from BHUPI.

The code transfer to swift as below:

Pay attention "allowLossyConversion: false"

if you set the value to true, it will show pure text.

let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"

        let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)

        UITextView_Message.attributedText = theAttributedString

For Swift3

    let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"

    let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)

    UITextView_Message.attributedText = theAttributedString

For some cases UIWebView is a good solution. Because:

  • it displays tables, images, other files
  • it's fast (comparing with NSAttributedString: NSHTMLTextDocumentType)
  • it's out of the box

Using NSAttributedString can lead to crashes, if html is complex or contains tables (so example)

For loading text to web view you can use the following snippet (just example):

func loadHTMLText(_ text: String?, font: UIFont) {
        let fontSize = font.pointSize * UIScreen.screens[0].scale
        let html = """
        <html><body><span style=\"font-family: \(font.fontName); font-size: \(fontSize)\; color: #112233">\(text ?? "")</span></body></html>
        """
        self.loadHTMLString(html, baseURL: nil)
    }

You can also use one more way. Three20 library offers a method through which we can construct a styled textView. You can get the library here: http://github.com/facebook/three20/

The class TTStyledTextLabel has a method called textFromXHTML: I guess this would serve the purpose. But it would be possible in readonly mode. I don't think it will allow to write or edit HTML content.

There is also a question which can help you regarding this: HTML String content for UILabel and TextView

I hope its helpful.


NSDoc save the text file in a string to an html file then simultaneously load it into a webview that is in the same place as your UITextView..

참고URL : https://stackoverflow.com/questions/2454067/display-html-text-in-uitextview

반응형