【问题标题】:NSString render HTML tags?NSString 渲染 HTML 标签?
【发布时间】:2011-09-17 14:07:23
【问题描述】:

我正在开发一个应用程序,该应用程序显示的内容也显示在该应用程序的网页版本上。我得到了与网页显示相同的标记文本,但在 UITextView 中。

文本嵌入了 HTML 标记,例如 <BR><p><em>,分别用于分隔符、段落和粗体(强调)。

是否有 NSString 或 UITextView 中的文本编码可以呈现 HTML 标签,就像它们在网页中显示一样?我想查看中断、新段落、粗体等,而不仅仅是剥离 html 标签。 提前致谢。

【问题讨论】:

    标签: html cocoa-touch nsstring rendering uitextview


    【解决方案1】:

    您可以使用UIWebView 代替UITextView 在您的iPhone 应用程序上查看HTML 内容。 NSString 存储为字符串。它不会渲染它。

    【讨论】:

    • 你能帮忙提供一个样本吗?根据我的阅读,您从 URL 加载 UIWebView。我没有要加载的 url,而只有 plist 中的 html 标记文本(NSString)。我没有看到像 UITextView 那样的 myWebView.text(或 myWebView.backgroundColor)方法。谢谢!
    【解决方案2】:

    以下是从 UIWebView 中的字符串加载 html 的简单代码。您可以使用其其他属性自定义您的 webview,对于 html 中的链接上的用户交互,您需要实现 UIWebView 委托。

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 0, 300, 300)];
    
    NSString *html = [NSString stringWithFormat:@"%@", YOUR_HTML_GOES_HERE];
    [webView loadHTMLString:html baseURL:[NSURL URLWithString:@""]];
    
    [self addSubview:webView];
    [webView release];
    

    【讨论】:

      【解决方案3】:

      您可以使用 UITextView 来使用 NSAttributedString 呈现 html,如下所示(适用于 iOS 7.0 及更高版本):

      NSAttributedString *attributedString = [[NSAttributedString alloc] 
      initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] 
                                         options:@{
                     NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType
                                                  }
                              documentAttributes:nil
                                           error:nil];
      textView.attributedText = attributedString;
      

      【讨论】:

        猜你喜欢
        • 2016-10-01
        • 1970-01-01
        • 2020-03-11
        • 1970-01-01
        • 2016-12-13
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多