fields objective-c ios uitextfield

objective c - fields - Objetivo C: ¿Cómo crear un UITextField multilínea?



text field ios 11 (2)

Posible duplicado:
¿Cómo crear un UITextfield multilínea?

¿Cómo puedo implementar un campo de texto de varias líneas como lo que veo en la aplicación de mensajería del iPhone?

Parece que una vez que la longitud de la entrada excede la longitud, se creará automáticamente una segunda línea.

EDITAR: actualizado para aclarar mis desafíos en el uso de un UITextView

Para mí, me gustaría modelar la sensación y el aspecto del UITextView a eso, como se muestra a continuación. No estoy seguro de cómo puedo hacerlo con UITextView como se sugiere. Por ejemplo

1) Cómo expandir el cuadro dinámicamente si mi texto necesita desbordarse a la siguiente línea

2) Cómo agregar el borde y el estilo como se muestra a continuación

3) Cómo adjuntar el cuadro de texto justo encima del teclado (en lugar de en la vista)

Sé que Instagram también tiene esto, si alguien puede indicarme la dirección correcta, será genial. Gracias de antemano


Compruebe estas respuestas:

¿Cómo crear un UITextfield multilínea?

¿Cómo crear un UITextfield multilínea?

http://brettschumann.com/blog/2010/01/15/iphone-multiline-textbox-for-sms-style-chat

Y definitivamente prueba Three20 que es una gran biblioteca utilizada en muchas aplicaciones como Facebook.

Edición: extracto extraído del blog BrettSchumann

#import <uikit uikit.h=""> @interface MultilineTextboxViewController : UIViewController { IBOutlet UIView *viewTable; IBOutlet UIView *viewForm; IBOutlet UITextView *chatBox; IBOutlet UIButton *chatButton; } @property (nonatomic, retain) UIView *viewTable; @property (nonatomic, retain) UIView *viewForm; @property (nonatomic, retain) UITextView *chatBox; @property (nonatomic, retain) UIButton *chatButton; - (IBAction)chatButtonClick:(id)sender; @end </uikit>

Con eso hecho, y mientras configuramos todo, vamos y agregamos nuestros elementos a nuestro archivo principal (.m) al mismo tiempo, sin olvidar también desasignarlos.

@synthesize viewTable; @synthesize viewForm; @synthesize chatBox; @synthesize chatButton; - (void)dealloc{ [viewTable release]; [viewForm release]; [chatBox release]; [chatButton release]; [super dealloc]; }

En el método (vacío) viewDidLoad necesitamos agregar algunos observadores de notificación para que podamos ver cuándo se muestra u oculta el teclado y cuando el usuario presiona una tecla del teclado.

- (void)viewDidLoad { //set notification for when keyboard shows/hides [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; //set notification for when a key is pressed. [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil]; //turn off scrolling and set the font details. chatBox.scrollEnabled = NO; chatBox.font = [UIFont fontWithName:@"Helvetica" size:14]; [super viewDidLoad]; }

Cuando se establece el enfoque en la vista de texto, se mostrará el teclado. Debido a que la vista de texto y los botones se encuentran en la parte inferior de viewForm en la pantalla, el teclado se montará y los revisará. Entonces, lo que queremos hacer es ajustar la altura de viewTable y la posición de viewForm. Hacemos esto en el siguiente método.

-(void) keyboardWillShow:(NSNotification *)note{ // get keyboard size and loction CGRect keyboardBounds; [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds]; // get the height since this is the main value that we need. NSInteger kbSizeH = keyboardBounds.size.height; // get a rect for the table/main frame CGRect tableFrame = viewTable.frame; tableFrame.size.height -= kbSizeH; // get a rect for the form frame CGRect formFrame = viewForm.frame; formFrame.origin.y -= kbSizeH; // animations settings [UIView beginAnimations:nil context:NULL]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationDuration:0.3f]; // set views with new info viewTable.frame = tableFrame; viewForm.frame = formFrame; // commit animations [UIView commitAnimations]; }

Ahora que se muestra el teclado y se han ajustado nuestras vistas, queremos capturar el texto que ingresa el usuario y ver si necesitamos realizar algún ajuste en el chatBox. Por suerte para nosotros, podemos usar el objeto CGSize, pasarle un poco de texto y decirle al tamaño del tamaño que queremos restringir el texto y desde allí podemos calcular la altura. Ahora es cuando entra una pequeña prueba y error. La línea varía con el tamaño de la fuente y el ancho de su objeto CGSize variará con el ancho de su UITextview, por lo que tendrá que experimentar un poco. El valor del uso de 12 en el siguiente código es la diferencia de altura entre la altura inicial de mi chatBox y la altura de la línea según la fuente que he establecido.

-(void) keyPressed: (NSNotification*) notification{ // get the size of the text block so we can work our magic CGSize newSize = [chatBox.text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:CGSizeMake(222,9999) lineBreakMode:UILineBreakModeWordWrap]; NSInteger newSizeH = newSize.height; NSInteger newSizeW = newSize.width; // I output the new dimensions to the console // so we can see what is happening NSLog(@"NEW SIZE : %d X %d", newSizeW, newSizeH); if (chatBox.hasText) { // if the height of our new chatbox is // below 90 we can set the height if (newSizeH <= 90) { [chatBox scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO]; // chatbox CGRect chatBoxFrame = chatBox.frame; NSInteger chatBoxH = chatBoxFrame.size.height; NSInteger chatBoxW = chatBoxFrame.size.width; NSLog(@"CHAT BOX SIZE : %d X %d", chatBoxW, chatBoxH); chatBoxFrame.size.height = newSizeH + 12; chatBox.frame = chatBoxFrame; // form view CGRect formFrame = viewForm.frame; NSInteger viewFormH = formFrame.size.height; NSLog(@"FORM VIEW HEIGHT : %d", viewFormH); formFrame.size.height = 30 + newSizeH; formFrame.origin.y = 199 - (newSizeH - 18); viewForm.frame = formFrame; // table view CGRect tableFrame = viewTable.frame; NSInteger viewTableH = tableFrame.size.height; NSLog(@"TABLE VIEW HEIGHT : %d", viewTableH); tableFrame.size.height = 199 - (newSizeH - 18); viewTable.frame = tableFrame; } // if our new height is greater than 90 // sets not set the height or move things // around and enable scrolling if (newSizeH > 90) { chatBox.scrollEnabled = YES; } } }

Una vez que estamos y el usuario presiona el botón de enviar, queremos hacer algo con nuestro texto, la palabra clave desaparecerá y queremos restablecer nuestra vista como estaban. ¿Entonces cómo hacemos eso?

- (IBAction)chatButtonClick:(id)sender{ // hide the keyboard, we are done with it. [chatBox resignFirstResponder]; chatBox.text = nil; // chatbox CGRect chatBoxFrame = chatBox.frame; chatBoxFrame.size.height = 30; chatBox.frame = chatBoxFrame; // form view CGRect formFrame = viewForm.frame; formFrame.size.height = 45; formFrame.origin.y = 415; viewForm.frame = formFrame; // table view CGRect tableFrame = viewTable.frame; tableFrame.size.height = 415; viewTable.frame = tableFrame; }

El resignFirstResponder va a ocultar el teclado y luego todo lo que tenemos que hacer es configurar las vistas y chatBox de nuevo a sus estados originales.

-(void) keyboardWillHide:(NSNotification *)note{ // get keyboard size and loction CGRect keyboardBounds; [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds]; // get the height since this is the main value that we need. NSInteger kbSizeH = keyboardBounds.size.height; // get a rect for the table/main frame CGRect tableFrame = viewTable.frame; tableFrame.size.height += kbSizeH; // get a rect for the form frame CGRect formFrame = viewForm.frame; formFrame.origin.y += kbSizeH; // animations settings [UIView beginAnimations:nil context:NULL]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationDuration:0.3f]; // set views with new info viewTable.frame = tableFrame; viewForm.frame = formFrame; // commit animations [UIView commitAnimations]; }

Y ahí está, una vista de texto que comienza como una sola línea y aumenta de tamaño a medida que el usuario ingresa el texto a un tamaño máximo antes de convertirse en una vista de texto en desplazamiento.


UITextField no le permite escribir más de una línea ... pero puede usar UITextView en UITextView lugar, y usar la función NSString -sizeWithFont para comprender la cantidad de espacio que necesita.

Me gusta esto:

CGSize size = [yourTextView.text sizeWithFont:yourTextView.font]; CGRect f = yourTextView.frame; f.size.height = ceil(size.width/f.size.width)*size.height yourTextView.frame = f;

No probé este código, pero ya usé un código como ese en el pasado. Espero que mis informaciones puedan ser útiles :)