如何在iPhone上显示来自API的HTML文本?

rph*_*ath 46 iphone objective-c uiwebview uitextview ios

解释我的情况的最好例子是使用博客文章.假设我有一个UITableView,它载有我从API获得的博客帖子的标题.当我点击一行时,我想显示详细的博文.

这样做时,API会传回几个字段,包括"post body"(HTML文本).我的问题是,我应该使用什么来显示它,以便它显示为格式化的HTML?我应该使用UIWebView吗?我不确定你是否在浏览网页时使用UIWebView(比如用URL或其他东西初始化它),或者你可以将它交给HTML字符串,它会正确地格式化它.

此页面上还会显示其他几个字段,例如标题,类别,作者等.我只是使用UILabel,所以没有问题.但我不知道如何处理HTML块.我正在以编程方式完成所有这些工作.顺便说一句.

如果你不能说,我对iOS开发相对较新,只有2-3周左右,没有obj-c背景.因此,如果UIWebView是正确的方法,我也会感激任何"陷阱!" 注意,如果有的话.

Mos*_*she 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];

}
Run Code Online (Sandbox Code Playgroud)

注意:

使用'NSMutableString'的好处是,您可以继续通过整个解析操作构建字符串,然后将其传递给'UIWebView',而创建后不能更改'NSString'.

  • 谢谢,正是我想要的. (2认同)

Ped*_*ace 9

   self.textLbl.attributedText = [[NSAttributedString alloc] initWithData:    [@"html-string" dataUsingEncoding:NSUnicodeStringEncoding]
                                                                          options:@{     NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType
                                                                                     } documentAttributes:nil error:nil];
Run Code Online (Sandbox Code Playgroud)


neh*_*eha 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];
Run Code Online (Sandbox Code Playgroud)

我正在使用此代码甚至设置webview文本的字体并传递我的ivar"ParameterWhereYouStoreTextFromAPI",我将存储从api获取的文本.


Ort*_*ntz 6

在原始HTML(文本样式,p/br标记)的特殊情况下,您还可以使用UITextView未记录的属性:

-[UITextView setValue:@"<b>bold</b>" forKey:@"contentToHTMLString"]
Run Code Online (Sandbox Code Playgroud)

即使它没有文档,它也被用于我所知道的许多应用程序中,并且到目前为止还没有引起任何拒绝.

  • `contentToHTMLString`键未记录. (2认同)