tutorial open iphone objective-c uiwebview

iphone - open - web view swift 4



El contenido HTML se ajusta a UIWebview sin alejarse (7)

Estoy utilizando UIWebView para renderizar algo de HTML. Sin embargo, aunque el ancho de mi vista web es 320, mi HTML aún se muestra con el ancho completo y se puede desplazar horizontalmente.

Quiero lograr lo mismo que logra la aplicación de correo nativa, que es que se ajusta a todo el contenido dentro de ese ancho sin tener que alejarse: ¿cómo la aplicación de correo nativo procesa HTML de esta manera?

Actualizar

Pensé que sería útil utilizar la metaetiqueta de la ventana gráfica, pero no pude hacer que esto funcionara.

Esto es lo que está sucediendo:

Como puede ver, el contenido no se ajusta al ancho del dispositivo. He intentado tantas combinaciones de metaetiquetas de viewport . El siguiente es un ejemplo de lo que sucede cuando intento la sugerencia de Martins.

El HTML original se puede encontrar here .

La forma en que este HTML es renderizado por la aplicación de correo nativo es así .


Esto es lo que haces:

En su controlador de UI que posee la vista web, UIWebViewDelegate en UIWebViewDelegate . Luego, cuando configure la URL para cargar, configure el delegado como el controlador:

NSString *urlAddress = @"http://dl.dropbox.com/u/50941418/2-build.html"; NSURL *url = [NSURL URLWithString:urlAddress]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [webView loadRequest:requestObj]; webView.delegate = self;

Y finalmente implemente el webViewDidFinishLoad: para establecer correctamente el nivel de zoom:

Esta opción será aplicable desde iOS 5.0 y>

- (void)webViewDidFinishLoad:(UIWebView *)theWebView { CGSize contentSize = theWebView.scrollView.contentSize; CGSize viewSize = theWebView.bounds.size; float rw = viewSize.width / contentSize.width; theWebView.scrollView.minimumZoomScale = rw; theWebView.scrollView.maximumZoomScale = rw; theWebView.scrollView.zoomScale = rw; }

Espero que esto ayude...

Opción B, puede intentar alterar el HTML (este ejemplo hace el trabajo pero no es perfecto desde el punto de vista del análisis de HTML. Solo quería ilustrar mi punto. Sí funciona para su ejemplo, y probablemente en la mayoría de los casos. 40 probablemente se pueda detectar mediante programación, no intenté investigar eso.

NSString *urlAddress = @"http://dl.dropbox.com/u/50941418/2-build.html"; NSURL *url = [NSURL URLWithString:urlAddress]; NSString *html = [NSString stringWithContentsOfURL:url encoding:[NSString defaultCStringEncoding] error:nil]; NSRange range = [html rangeOfString:@"<body"]; if(range.location != NSNotFound) { // Adjust style for mobile float inset = 40; NSString *style = [NSString stringWithFormat:@"<style>div {max-width: %fpx;}</style>", self.view.bounds.size.width - inset]; html = [NSString stringWithFormat:@"%@%@%@", [html substringToIndex:range.location], style, [html substringFromIndex:range.location]]; } [webView loadHTMLString:html baseURL:url];


Lo que funcionó para mí fue seleccionar UIWebView en Interface Builder y marcar la casilla que dice "Escala de página para ajustar":


Normalmente, debe usar la metaetiqueta de la ventana gráfica. Pero su uso es muy errático, sobre todo si quieres una página web multiplataforma.

También depende de qué contenido y CSS tengas.

Para la página de inicio de mi iPhone, que debe cambiar el tamaño automáticamente de vertical a paisaje, utilizo esto:

<meta name="viewport" content="width=device-width; minimum-scale=1.0; maximum-scale=1.0; user-scalable=no">

Si necesita un cambio de tamaño especial, también puede usar el evento:

<body onorientationchange="updateOrientation();">

con el funciton correspondiente en tu javascript:

function updateOrientation() { if(Math.abs(window.orientation)==90) // landscape else // portrait }

EDITAR:

Al ver su fuente de la página, parece que lo hizo con un editor web, ¿no?

Vale, entiendo. Tu div principal tiene un ancho de 600px. La resolución de la pantalla del iphone es 320x480. 600> 320 por lo que excede los límites de la pantalla.

Ahora, hagamos algunas operaciones simples:

320 / 600 = 0.53 480 / 600 = 0.8

Por lo tanto, quiere alejar 0.5 veces como mínimo y 0.8 veces como máximo. Vamos a cambiar la ventana gráfica:

<meta name="viewport" content="width=device-width; minimum-scale=0.5; maximum-scale=0.8; user-scalable=no">


Puede generar un NSAttributedString desde HTML (hágalo en el fondo):

@implementation NSAttributedString (Utils) + (void)parseHTML:(NSString *)html withCompletion:(void (^)(NSAttributedString *completion, NSError *error))completion { dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ NSError * __autoreleasing *error = nil; NSAttributedString *result = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:error]; NSError *safeError = (error != nil) ? *error : nil; dispatch_sync(dispatch_get_main_queue(), ^(void){ completion(result, safeError); }); }); } @end

Y muéstralo a través de la instancia UITextView :

[NSAttributedString parseHTML:htmlString withCompletion:^(NSAttributedString *parseResult, NSError *error) { bodyTextView.attributedText = parseResult; }];

Algunas características de diseño, sin embargo, pueden corromperse con este enfoque.


Solo agrega esto:

webView.scalesPageToFit = YES;


Swift 3:

Use esta extensión para cambiar el tamaño del contenido de la vista web de acuerdo con el tamaño de una vista web.

extension UIWebView { ///Method to fit content of webview inside webview according to different screen size func resizeWebContent() { let contentSize = self.scrollView.contentSize let viewSize = self.bounds.size let zoomScale = viewSize.width/contentSize.width self.scrollView.minimumZoomScale = zoomScale self.scrollView.maximumZoomScale = zoomScale self.scrollView.zoomScale = zoomScale } }

¿Cómo invocar?

webViewOutlet.resizeWebContent()


@implementation UIWebView (Resize) - (void)sizeViewPortToFitWidth { [self stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.querySelector(''meta[name=/"viewport/"]'').setAttribute(''content'', ''width=%d;'', false); ", (int)self.frame.size.width]]; } @end