iOS: campo de texto

Uso del campo de texto

Un campo de texto es un elemento de la interfaz de usuario que permite a la aplicación obtener información del usuario.

A continuación se muestra un campo UITextfield.

Propiedades importantes del campo de texto

  • Texto de marcador de posición que se muestra cuando no hay entrada de usuario
  • Texto normal
  • Tipo de corrección automática
  • Tipo de teclado
  • Tipo de clave de retorno
  • Modo de botón claro
  • Alignment
  • Delegate

Actualización de propiedades en xib

Puede cambiar las propiedades del campo de texto en xib en el inspector de atributos en el área de utilidades (lado derecho de la ventana).

Delegados de campo de texto

Podemos configurar el delegado en el generador de interfaces haciendo clic con el botón derecho en UIElement y conectarlo al propietario del archivo como se muestra a continuación.

Pasos para usar delegados

Step 1 - Configure el delegado como se muestra en la figura anterior.

Step 2 - Agregue un delegado al que responde su clase.

Step 3 - Implementar los delegados de campo de texto, los delegados de campo de texto importantes son los siguientes -

- (void)textFieldDidBeginEditing:(UITextField *)textField 
- (void)textFieldDidEndEditing:(UITextField *)textField

Step 4 - Como sugiere el nombre, los dos delegados anteriores se llaman una vez que comenzamos a editar el campo de texto y finalizamos la edición, respectivamente.

Step 5 - Para otros delegados, consulte la referencia del protocolo UITextDelegate.

Ejemplo de código y pasos

Step 1 - Usaremos la aplicación de muestra creada para elementos de la interfaz de usuario.

Step 2 - Nuestra clase ViewController adoptará UITextFieldDelegate y nuestro ViewController.h El archivo se actualiza de la siguiente manera:

#import <UIKit/UIKit.h>

// You can notice the adddition of UITextFieldDelegate below
@interface ViewController : UIViewController<UITextFieldDelegate>

@end

Step 3 - Luego agregamos un método addTextField a nuestro archivo ViewController.m.

Step 4 - Luego llamamos a este método en nuestro método viewDidLoad.

Step 5 - actualización viewDidLoad en ViewController.m como sigue -

#import "ViewController.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   //The custom method to create our textfield is called
   
   [self addTextField];
   // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}

-(void)addTextField {
   // This allocates a label 
   UILabel *prefixLabel = [[UILabel alloc]initWithFrame:CGRectZero];
   
   //This sets the label text
   prefixLabel.text [email protected]"## ";
   
   // This sets the font for the label
   [prefixLabel setFont:[UIFont boldSystemFontOfSize:14]];
   
   // This fits the frame to size of the text
   [prefixLabel sizeToFit];
	
   // This allocates the textfield and sets its frame
   UITextField *textField = [[UITextField  alloc] initWithFrame:
   CGRectMake(20, 50, 280, 30)];
   
   // This sets the border style of the text field 
   textField.borderStyle = UITextBorderStyleRoundedRect;
   textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
   [textField setFont:[UIFont boldSystemFontOfSize:12]];
   
   //Placeholder text is displayed when no text is typed
   textField.placeholder = @"Simple Text field";
   
   //Prefix label is set as left view and the text starts after that
   textField.leftView = prefixLabel;
  
   //It set when the left prefixLabel to be displayed
   textField.leftViewMode = UITextFieldViewModeAlways;
  
   // Adds the textField to the view.
   [self.view addSubview:textField];
  
   // sets the delegate to the current class
   textField.delegate = self;
}

// pragma mark is used for easy access of code in Xcode
#pragma mark - TextField Delegates

// This method is called once we click inside the textField
-(void)textFieldDidBeginEditing:(UITextField *)textField {
   NSLog(@"Text field did begin editing");
}

// This method is called once we complete editing
-(void)textFieldDidEndEditing:(UITextField *)textField {
   NSLog(@"Text field ended editing");
}

// This method enables or disables the processing of return key
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
   [textField resignFirstResponder];
   return YES;
}

- (void)viewDidUnload {
   label = nil;
   [super viewDidUnload];
}
@end

Step 6 - Cuando ejecutamos la aplicación, obtendremos el siguiente resultado.

Step 7- Los métodos delegados se llaman en función de la acción del usuario. Vea la salida de la consola para saber cuándo se llama a los delegados.