如何在iPhone上从API显示HTML文本?

47

用一篇博客文章来解释我的情况是最好的例子。假设我有一个加载了博客文章标题的UITableView,这些标题都是从API获取的。当我点击某行时,我想显示详细的博客文章内容。

在这样做时,API会返回多个字段,包括“帖子正文”(这是HTML文本)。我的问题是,我应该使用什么来显示它,以便它以格式化的HTML形式显示?我应该使用UIWebView吗?我不确定在查看网页时是否使用UIWebView(例如使用URL初始化它或其他方式),或者您可以将HTML字符串传递给它并且它将正确地格式化它。

此页面上将显示其他几个字段,例如标题、类别、作者等。对于这些字段,我只是使用UILabels,所以没有问题。但是我不知道如何处理HTML块。顺便说一下,我正在以编程方式完成所有这些操作。

如果您无法判断,那么我相对较新于iOS开发,只有大约2-3周时间,并且没有obj-c背景。因此,如果UIWebView是正确的方法,我还将感谢任何“陷阱!”注释,如果有的话。

8个回答

54

正如David Liu所说,UIWebview 是正确的选择。我建议先构建 HTML 字符串,然后再将其传递给 UIWebView。此外,我会使用 [webView setBackgroundColor:[UIColor clearColor]] 来使背景透明,这样你可以更轻松地设置页面布局。

以下是一个示例代码:

- (void) createWebViewWithHTML{
    //create the string
    NSMutableString *html = [NSMutableString stringWithString: @"<html><head><title></title></head><body style=\"background:transparent;\">"];

    //continue building the string
    [html appendString:@"body content here"];
    [html appendString:@"</body></html>"];

    //instantiate the web view
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame];

    //make the background transparent
    [webView setBackgroundColor:[UIColor clearColor]];

    //pass the string to the webview
    [webView loadHTMLString:[html description] baseURL:nil];

    //add it to the subview
    [self.view addSubview:webView];

}

注意:

使用'NSMutableString'的好处是,您可以在整个解析过程中继续构建字符串,然后将其传递给'UIWebView',而'NSString'一旦创建就无法更改。


这个 viewDidLoad 会是什么样子? - Realinstomp
小心使用UIWebView时的内存占用。 - Felipe Baytelman
这对可访问性来说很糟糕。UIWebview不能轻易地识别设备的可访问文本大小。 - funkybro

9
   self.textLbl.attributedText = [[NSAttributedString alloc] initWithData:    [@"html-string" dataUsingEncoding:NSUnicodeStringEncoding]
                                                                          options:@{     NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType
                                                                                     } documentAttributes:nil error:nil];

7
NSString *strForWebView = [NSString stringWithFormat:@"<html> \n"
      "<head> \n"
      "<style type=\"text/css\"> \n"
      "body {font-family: \"%@\"; font-size: %@; height: auto; }\n"
      "</style> \n"
      "</head> \n"
      "<body>%@</body> \n"
      "</html>", @"helvetica", [NSNumber numberWithInt:12], ParameterWhereYouStoreTextFromAPI];


 [self.webview loadHTMLString:strForWebView baseURL:nil];

我正在使用这段代码来设置webview文本的字体,并传递我的ivar 'ParameterWhereYouStoreTextFromAPI',其中我存储从api获取的文本。

6
在原始的HTML文本(文本样式,p/br标签)的特殊情况下,您也可以使用一个未记录的属性UITextView
-[UITextView setValue:@"<b>bold</b>" forKey:@"contentToHTMLString"]

尽管它没有文档说明,但我所知道的许多应用程序都在使用它,而且迄今为止还没有引起任何拒绝。


从技术上讲,setValue:forKey:并非未经记录的。 - Felipe Baytelman
2
contentToHTMLString 键未被记录在文档中。 - Ortwin Gentz

4
你可以使用UIWebView的-loadHTMLString:baseURL:方法。
参考链接:这里

2
如何使UIWebView透明


0

您可以通过删除HTML/JS文本(如align、centre、br>)来显示它。如果您的目标是iOS7.0及以上版本,请使用这些方法。

    NSString *htmlFile;

    htmlFile=[array valueForKey:@"results"];

    NSAttributedString *attr = [[NSAttributedString alloc] initWithData:[htmlFile dataUsingEncoding:NSUTF8StringEncoding]options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)}documentAttributes:nil error:nil];
        NSLog(@"html: %@", htmlFile);
        NSLog(@"attr: %@", attr);
        NSLog(@"string: %@", [attr string]);
        NSString *finalString = [attr string];

        [webView loadHTMLString:[finalString description] baseURL:nil];

0
我的情境是:我在一个视图控制器中有一个TextView,并且必须在TextView中显示HTML格式的数据。
Swift 3:
func detectUrlInText() {

let attrStr = try! NSAttributedString(
            data: "<b><i>\(Ldesc)</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)

 desc.attributedText = attrStr

 desc.font = UIFont(name: "CALIBRI", size: 14)

}
// Ldesc is the string which gives me the data to put in the textview. desc is my UITextView.
:)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接