Quiero crear una vista, como el cuadro de diálogo compartido de la aplicación Facebook o Twitter, por ejemplo, donde solo hay una UITextView y un teclado permanente. Puedo ver cómo comenzar con el teclado visible desde this answer, pero no estoy seguro de cómo ajustar el tamaño del UITextView para que encaje exactamente encima del teclado. Si no lo hago, el texto puede ocultarse debajo del teclado, lo cual es incómodo.¿Cómo creo un UITextView que se ajuste exactamente sobre el teclado?
Respuesta
He encontrado un ejemplo de código útil en la documentación de Apple para esto: https://developer.apple.com/library/ios/#samplecode/KeyboardAccessory/Introduction/Intro.html
Aquí está el código que terminó con. No me preocupa el ocultamiento del teclado, ya que, desde mi punto de vista, el teclado nunca debería esconderse.
- (void)viewWillAppear:(BOOL)flag
{
[super viewWillAppear:flag];
// Listen for the keyboard to show up so we can get its height
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
// Set focus on the text view to display the keyboard immediately
[self.textView becomeFirstResponder];
}
- (void)keyboardWillShow:(NSNotification *)notification
{
/*
Reduce the size of the text view so that it's not obscured by the keyboard.
*/
NSDictionary *userInfo = [notification userInfo];
// Get the origin of the keyboard when it's displayed.
NSValue* keyboardFrame = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
// Get the top of the keyboard as the y coordinate of its origin in self's view's
// coordinate system. The bottom of the text view's frame should align with the
// top of the keyboard's final position.
CGRect keyboardRect = [keyboardFrame CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
// Set the text view's frame height as the distance from the top of the view bounds
// to the top of the keyboard
CGFloat keyboardTop = keyboardRect.origin.y;
CGRect newTextViewFrame = self.view.bounds;
newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
self.textView.frame = newTextViewFrame;
}
puedo encontrar esta página siempre es bastante útil - que muestra todos los tamaños importantes, por lo que es fácil de calcular el tamaño que necesita:
Puede suscribirse a UIKeyboardWillShowNotification
. La notificación incluye el marco del teclado, por lo que puede ajustar el tamaño de la vista para que se ajuste al espacio restante.
Usted puede obtener el tamaño del teclado, así:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardIsUp:) name:UIKeyboardDidShowNotification object:nil];
- (void)keyboardIsUp:(NSNotification *)notification{
CGSize keyboardSize = [self.view convertRect:[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil].size;
NSLog(@"%f", keyboardSize.height);
}
modo horizontal [EDIT]
lo probé en el iPas simulador y devolverlo 264 en el modo de retrato de un teclado QWERTY, pero cuando inicia la aplicación o gira al modo horizontal, devuelve 1024. Por lo tanto, es posible que deba solicitar el ancho en lugar de la altura en modo horizontal ...
[EDITAR]
Gracias al comentario de Rob mayoff no hay ningún problema con el modo de paisaje más
[EDIT]
Ésta no es la mejor forma de hacerlo, pero que da una idea. Voy a echar un vistazo atrás en ello más tarde
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
CGSize size = [self.view convertRect:self.view.frame toView:nil].size;
CGFloat width = size.width;
CGFloat height = 40;
CGFloat x = 0;
CGFloat y = size.height+40;
aboveKBView = [[[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)] autorelease];
[aboveKBView setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:aboveKBView];
}
- (void)keyboardWillHide:(NSNotification *)notification{
[aboveKBView setHidden:YES];
}
- (void)keyboardWillShow:(NSNotification *)notification{
NSLog(@"keyboardIsUp");
CGSize keyboardSize = [self.view convertRect:[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil].size;
CGSize size = [self.view convertRect:self.view.frame toView:nil].size;
CGFloat width = size.width;
CGFloat height = 40;
CGFloat x = 0;
CGFloat y = size.height-(keyboardSize.height+height);
[aboveKBView setFrame:CGRectMake(x, y, width, height)];
[aboveKBView setHidden:NO];
}
El marco en la notificación está en coordenadas globales. Necesita convertirlo al sistema de coordenadas apropiado usando algo como '[myView convertRect: keyboardFrame fromView: nil]'. –
Gracias por la punta –
Eso funciona para obtener el tamaño, pero todavía tengo problemas para configurar el UITextView a la altura correcta. En el código a continuación frame.size.heigh es 367, y keyboardHeight es 216, pero por alguna razón cuando llamo a setFrame hay espacio entre la vista de texto y el teclado. FYI, estoy configurando el observador y llamando '[self.textView becomeFirstResponder]' en 'viewWillAppear'. –
probar este
en viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
y añadir a estos métodos.
- (void) keyboardWillShow: (NSNotification*) aNotification;
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
CGRect rect = [[self view] frame];
rect.origin.y -= 60;
[[self view] setFrame: rect];
[UIView commitAnimations];
}
- (void) keyboardWillHide: (NSNotification*) aNotification;
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
CGRect rect = [[self view] frame];
rect.origin.y += 60;
[[self view] setFrame: rect];
[UIView commitAnimations];
}
- 1. Cómo deshabilitar el teclado en una UITextView?
- 2. ¿Cómo se muestra el teclado de forma predeterminada en UITextView?
- 3. ¿Cómo hacer una UITableViewCell con una UITextView adentro, que ajuste dinámicamente su altura, sobre la base de UITextView?
- 4. ¿Cómo descarto una UITextView usando el botón del teclado Hecho?
- 5. ¿Cómo puedo hacer que UITextView se desplace correctamente cuando el teclado está visible?
- 6. Ocultando el teclado al perder el foco en un UITextView
- 7. ¿Cómo creo un UITextField transparente?
- 8. ¿Cómo se hace que un componente UIPickerView se ajuste?
- 9. ¿Cómo creo una marca de tiempo de unix que no se ajuste para localtime?
- 10. Jquery Draggable - ¿Cómo creo un nuevo div arrastrable sobre la marcha que luego se puede arrastrar?
- 11. encargo del iPhone teclado, que tiene un problema con el botón de retroceso en UITextView
- 12. ¿Cómo se reduce el contenido para que se ajuste a un div?
- 13. ¿Cómo se ejecuta exactamente un script PHP?
- 14. ThreeJS: ¿Crear una imagen de fondo que se ajuste exactamente a la ventana?
- 15. ¿Cómo hacer que FigureCanvas se ajuste a un panel?
- 16. UITextView no aparece hasta que se desplaza
- 17. Tecla Listo en la aplicación iPhone que cierra el teclado (con UITextView)
- 18. iTextSharp: ¿Cómo cambiar el tamaño de una imagen para que se ajuste a un tamaño fijo?
- 19. Cómo hacer un ajuste de palabra UILabel
- 20. Evitar que se descarte el teclado suave
- 21. ¿Cómo le doy un enfoque UITextView programáticamente?
- 22. UITextView inputView
- 23. Forzar el teclado para que se muestre mediante el botón (iOS)
- 24. ¿Cómo creo un enlace singleton que caduque?
- 25. C#: ¿cómo creo un programa que ejecutará el código que pinche en un cuadro de texto?
- 26. ¿Cómo puedo visualizar mi diseño de desplazamiento sobre el teclado?
- 27. ¿Cómo escalar/cambiar el tamaño del texto para que se ajuste a un TextView?
- 28. Cómo ocultar el teclado - de - iPhone UITextView - mediante la tecla de retorno
- 29. Añadir un botón para ocultar el teclado
- 30. Evitar que TextView se ajuste en el elemento primario
No todos los teclados son del mismo tamaño. "Chino - Simplificado (trazo)", por ejemplo. –