2010-11-09 4 views
43

El mejor ejemplo para explicar mi situación es usar una publicación de blog. Digamos que tengo una UITableView cargada con el título de las publicaciones de blog que obtuve de una API. Cuando hago clic en una fila, quiero mostrar la publicación detallada del blog.¿Cómo mostrar el texto HTML de la API en el iPhone?

Al hacer eso, la API devuelve varios campos, incluido el "cuerpo del mensaje" (que es texto HTML). Mi pregunta es, ¿qué debería usar para mostrarla para que aparezca como HTML formateado? ¿Debo usar UIWebView para eso? No estoy seguro si usa UIWebView cuando está viendo literalmente una página web (como inicializarla con una URL o algo así) o si puede entregarle una cadena HTML y la formateará correctamente.

Hay varios otros campos que se mostrarán en esta página, como título, categoría, autor, etc. Solo estoy usando UILabels para esos, así que no hay problemas allí. Pero no sé qué hacer con el fragmento de HTML. Estoy haciendo todo esto programáticamente, por cierto.

Si no puede decirlo, soy relativamente nuevo en el desarrollo de iOS, solo unas 2-3 semanas, sin antecedentes obj-c. Entonces, si UIWebView es el enfoque correcto, también agradecería cualquier "¡puaj!" notas, si hay alguna.

Respuesta

53

Como dijo David Liu, UIWebview es el camino a seguir. Recomendaría algunos construir la cadena HTML por separado y luego pasarla a UIWebView. Además, haré que el fondo sea transparente, usando [webView setBackgroundColor:[UIColor clearColor]] para que le resulte más fácil hacer que las cosas se vean como deberían.

Aquí está un ejemplo de código:

- (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]; 

} 

NOTA:

El beneficio de usar un 'NSMutableString' es que se puede seguir construyendo su cadena a través de toda una operación de análisis y luego pasarlo al 'UIWebView', mientras que un 'NSString' no se puede cambiar una vez creado.

+2

Gracias, exactamente lo que estaba buscando. – rpheath

+0

¿Cómo se vería el 'viewDidLoad' para esto? – Realinstomp

+0

Tenga cuidado con la memoria de UIWebView use –

4

Puede usar el método UIWebView's - loadHTMLString: baseURL :.

enlace Referencia: here

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]; 

Estoy usando este código para establecer incluso el tipo de letra para el texto en vista web y pasando mi Ivar 'ParameterWhereYouStoreTextFromAPI donde estoy almacenar texto obtenida de API.

+0

¡Eres increíble! me salvó. gracias :) –

6

En el caso especial de HTML primitiva (estilos de texto, p etiquetas/BR) también se puede utilizar UITextView con una propiedad no documentada:

-[UITextView setValue:@"<b>bold</b>" forKey:@"contentToHTMLString"] 

Aunque no está documentado, se usa en muchas aplicaciones que conozco y hasta el momento no ha causado un solo rechazo.

+0

Técnicamente, setValue: forKey: NO está sin documentar. –

+2

La clave 'contentToHTMLString' no está documentada. –

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

Puede demostrarlo mediante la eliminación de texto HTML/JS como (alinear, centrar, br>). Por favor, use estos métodos si se dirigen a iOS7.0 y superior.

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

Mi escenario: Tengo una vista de texto en un controlador de vista y tengo que mostrar datos en el textView que está en formato 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. 
:) 
Cuestiones relacionadas