texto predictivo developer app iphone cordova iphone-softkeyboard

developer - texto predictivo iphone



¿Mostrar programáticamente el teclado suave en iPhone en una aplicación PhoneGap? (7)

¿Has probado usar Native Controls y llamarlos desde Javascript?

Aquí tiene un código que muestra el uso de Native Controls en una aplicación Phonegap Cordova (Phonegap 1.5)

https://gist.github.com/1384250

Espero que ayude a resolver el problema :)

He estado buscando por mucho tiempo, y hasta este momento, no encontré una solución funcional para las aplicaciones PhoneGap / Cordova que mostrarían el teclado virtual mediante programación.

Guión:

Tenemos una aplicación PhoneGap, un sitio web creado en jQuery Mobile, que en un momento muestra un diálogo para el usuario. Este diálogo también es una página web y tiene un solo cuadro de texto INPUT donde el usuario debe ingresar un código.

Problema:

Cuando se muestra el cuadro de diálogo del código, el cuadro de entrada se enfoca usando JavaScript . Sin embargo, debido a las restricciones impuestas en el navegador interno del iPhone, el teclado virtual no aparece hasta que el usuario realmente hace clic dentro del cuadro de texto de entrada.

Lo que probamos:

  • creando un cuadro de texto oculto y convirtiéndolo en el primer respondedor
  • hacer que la vista web real sea ​​una primera respuesta una vez que la entrada recibe el foco a través de JavaScript
  • usando sendActionsForControlEvents para probar y entregar Touch events a la vista web (aunque si alguien tiene un código de trabajo para una aplicación PhoneGap, agradecería que ellos pudieran compartirlo, ya que no soy profesional en la codificación de iOS)

¿Algunas ideas?

EDITAR: la restricción mencionada en esta pregunta es solo para navegadores incorporados ... si apunta a Opera, tendrá éxito usando el siguiente código:

var e = jQuery.Event("keydown", { keyCode: 37 }); $(''#element'').focus().trigger(e);

EDIT2: Este es un código PhoneGap final que puede usarse en un plugin:

keyboardhelper.h

// // keyboardHelper.h // soft keyboard displaying plugin for PhoneGap // // Copyright 2012 Martin Ambrus. // #import <Foundation/Foundation.h> #ifdef CORDOVA_FRAMEWORK #import <Cordova/CDVPlugin.h> #else #import "CDVPlugin.h" #endif @interface keyboardHelper : CDVPlugin { NSString *callbackID; } @property (nonatomic, copy) NSString *callbackID; - (void)showKeyboard:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options; @end

keyboardhelper.m

// // keyboardHelper.m // soft keyboard displaying plugin for PhoneGap // // Copyright 2012 Martin Ambrus. // #import "keyboardHelper.h" #import "AppDelegate.h" @implementation keyboardHelper @synthesize callbackID; -(void)showKeyboard:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options { self.callbackID = [arguments pop]; //Get text field coordinate from webview. - You should do this after the webview gets loaded //myCustomDiv is a div in the html that contains the textField. int textFieldContainerHeightOutput = [[((AppDelegate *)[[UIApplication sharedApplication] delegate]).viewController.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(/"myCustomDiv/").offsetHeight;"] intValue]; int textFieldContainerWidthOutput = [[((AppDelegate *)[[UIApplication sharedApplication] delegate]).viewController.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(/"myCustomDiv/").offsetWidth;"] intValue]; int textFieldContainerYOffset = [[((AppDelegate *)[[UIApplication sharedApplication] delegate]).viewController.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(/"myCustomDiv/").offsetTop;"] intValue]; int textFieldContainerXOffset = [[((AppDelegate *)[[UIApplication sharedApplication] delegate]).viewController.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(/"myCustomDiv/").offsetLeft;"] intValue]; UITextField *myTextField = [[UITextField alloc] initWithFrame: CGRectMake(textFieldContainerXOffset, textFieldContainerYOffset, textFieldContainerWidthOutput, textFieldContainerHeightOutput)]; [((AppDelegate *)[[UIApplication sharedApplication] delegate]).viewController.webView addSubview:myTextField]; myTextField.delegate = self; CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @"ok"]; [self writeJavascript:[pluginResult toSuccessCallbackString:self.callbackID]]; } -(BOOL)textFieldShouldReturn:(UITextField *)textField { //here you create your request to the server return NO; } -(BOOL)textFieldDidEndEditing:(UITextField *)textField { //here you create your request to the server return NO; } @end

javascript

var keyboardHelper = { showKeyboard: function(types, success, fail) { return Cordova.exec(success, fail, "keyboardHelper", "showKeyboard", types); } };


Admito que esto es privado, pero podría ayudarte:

@class UIKeyboard; void showKeyboard() { static UIKeyboard *kb = nil; if ([[UIKeyboard class] respondsToSelector:@selector(automaticKeyboard)]) kb = [UIKeyboard automaticKeyboard]; else kb = [UIKeyboard activeKeyboard]; if (kb == nil) { kb = [[[UIKeyboard alloc] initWithDefaultSize] autorelease]; [[[UIApplication sharedApplication] keyWindow] addSubview:kb]; } if ([kb respondsToSelector:@selector(orderInWithAnimation:)]) { [kb orderInWithAnimation:YES]; } else { [kb activate]; [kb minimize]; [kb maximize]; } }

Y llámalo así:

showKeyboard();


Antes de iOS 6, Apple solo permitía que el teclado apareciera tras una interacción del usuario. En iOS 6, han introducido la siguiente propiedad para UIWebView, que simplemente debe establecer en NO.

"yourWebView".keyboardDisplayRequiresUserAction = NO;

Apple establece esto por defecto a "Sí". Ahora puede llamar a focus() en su JS y aparecerá el teclado.


De hecho, acabo de encontrar una solución a esto . Como dice horak y como se describe en este artículo , con o sin teclado virtual, ahora es posible lograr esto con iOS 6.0 utilizando: KeyboardDisplayRequiresUserAction = NO;

A partir de Cordova 2.2, la propiedad iOS mencionada anteriormente simplemente puede agregarse al archivo Cordova.plist :

KeyboardDisplayRequiresUserAction, boolean, NO

Esto lo resuelve todo para todos los que usan Cordova 2.2. Ahora solo llame a input.focus () como se discutió anteriormente, y el teclado aparecerá automáticamente. Para aquellos de nosotros que aún no hemos actualizado nuestro Cordova a la última versión (2.2), afortunadamente todavía es posible .

Mostrar programáticamente el teclado en iPhone usando cordova v. <2.2

Paso 1 : Agregar propiedad a Cordova.plist

Vaya a su proyecto> Recursos> Cordova.plist. Agregar: KeyboardDisplayRequiresUserAction, boolean, NO

Paso 2 : agregar el siguiente fragmento de código a CDVViewController.m

Busque "@interface CDVViewController" (o similar para localizar el archivo anterior). Para Cordova 2.1, vaya a la línea 240 (todos los demás van a una línea después de una declaración " IsAtLeastiOSVersion " si, lo siento no puede ser más preciso que eso.) Agregue este fragmento de código a su CDVViewController.m en la línea mencionada anteriormente:

if (IsAtLeastiOSVersion(@"6.0")) { BOOL keyboardDisplayRequiresUserAction = YES; // KeyboardDisplayRequiresUserAction - defaults to YES if ([self.settings objectForKey:@"KeyboardDisplayRequiresUserAction"] != nil) { if ([self.settings objectForKey:@"KeyboardDisplayRequiresUserAction"]) { keyboardDisplayRequiresUserAction = [(NSNumber*)[self.settings objectForKey:@"KeyboardDisplayRequiresUserAction"] boolValue]; //JB-VAL121212 } } // property check for compiling under iOS < 6 if ([self.webView respondsToSelector:@selector(setKeyboardDisplayRequiresUserAction:)]) { [self.webView setValue:[NSNumber numberWithBool:keyboardDisplayRequiresUserAction] forKey:@"keyboardDisplayRequiresUserAction"]; } }

Descargo de responsabilidad : Esto ha sido probado solo en Cordova 2.1, sin embargo, es muy probable que todavía funcione con la versión 2.0 o cualquier otra versión anterior que viene con el archivo CDVViewController.m


Puede obtener las coordenadas para el campo de entrada usando javascript en webView. Luego, coloque su propio campo de texto sobre él y en su método de delegado textFieldShouldReturn envíe una solicitud al servidor con el código que el usuario ingresó.

//Get text field coordinate from webview. - You should do this after the webview gets loaded //myCustomDiv is a div in the html that contains the textField. int textFieldContainerHeightOutput = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(/"myCustomDiv/").offsetHeight;"] intValue]; int textFieldContainerWidthOutput = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(/"myCustomDiv/").offsetWidth;"] intValue]; int textFieldContainerYOffset = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(/"myCustomDiv/").offsetTop;"] intValue]; int textFieldContainerXOffset = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(/"myCustomDiv/").offsetLeft;"] intValue]; myTextField.frame = CGRectMake(textFieldContainerXOffset, textFieldContainerYOffset, textFieldContainerWidthOutput, textFieldContainerHeightOutput); [webView addSubview:myTextField]; myTextField.delegate = self;

Luego implementa textFieldShouldReturn y crea allí su solicitud al servidor.

-(BOOL)textFieldShouldReturn:(UITextField *)textField { //here you create your request to the server return NO; }

Esto se hace en un proyecto existente, sin embargo, sin usar PhoneGap. Espero que pueda adaptarlo a sus necesidades.

Para eliminar el campo de texto, puede ocultarlo

myTextField.hidden = YES;

o

myTextField = nil;

o

[myTextField removeFromSuperView];


Puede resolver el problema con una entrada config.xml estos días, agregue:

<preference name="keyboardDisplayRequiresUserAction" value="false" />


Puede usar el evento FocusOut en el campo de entrada y se disparará cuando se presione la tecla Listo. Podría usar esto en iOS 6 y superior. Creo que también funcionará en versiones anteriores.