iOS create UITextField programmatically

UITextField is a type of view which can display a value just like the UILabel and also lets the user change it on the screen using the keyboard. In this example we learn the following
  • Programmatically create UITextField and add them to the current view 
  • Set the border style 
  • Overlay custom views such as currency symbol, search icon, etc inside the view 
  • Vertical and Horizontal alignment of the Text 
  • Associate various keyboard types with the input text view 
  • Display Hint to the user when the text field is empty 
  • Display clear button on the text field 
  • Listen for events using the UITextField Delegate 
  • Restrict data entry to only certain types such as numeric only 
  • Restrict the number of maximun number of characters that are allowed in the text field

iOS UITextField with numeric data entry and view overlay
iOS create UITextField programmatically
iOS UITextField for email address
Create a new Project to create an iOS application with template as Single View Application. In the Product Name and Class prefix enter "UITextField". Check the box "Use Automatic Reference Counting" (ARC) and then choose where you want to create your project.
iOS UITextField Project

Interface file for the view controller - UITextFieldViewController.h

#import <UIKit/UIKit.h>

@interface UITextFieldViewController : UIViewController <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *myTextField;
@property (nonatomic, strong) UILabel *myLabel;

@end

Implementation file for the view controller - UITextFieldViewController.m

#import "UITextFieldViewController.h"

@interface UITextFieldViewController ()

@end

@implementation UITextFieldViewController

@synthesize myTextField, myLabel;

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //create a label with the local currency symbol
    UILabel *dollarSign = [[UILabel alloc] initWithFrame:CGRectZero];
    dollarSign.text = [[[NSNumberFormatter alloc] init] currencySymbol];
    [dollarSign sizeToFit];
    
    //create a label to display current user interaction with our editable text views
    CGRect myFrame = CGRectMake(10.0f, 10.0f, 250.0f, 40.0f);
    self.myLabel = [[UILabel alloc] initWithFrame:myFrame];
    self.myLabel.text = @"Start typing...";
    self.myLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    self.myLabel.textAlignment =  NSTextAlignmentLeft;
    [self.view addSubview:self.myLabel];
    
    //lets create 3 UITextViews on the screen
    for (NSInteger i=1; i<4; i++) {
        
        //set the origin of the frame reference
        myFrame.origin.y += myFrame.size.height + 10.0f;
        //create the text field
        self.myTextField = [[UITextField alloc] initWithFrame:myFrame];
        //set the border style for the text view
        self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
        
        
        switch (i) {
            
            case 1:
                //the vertical alignment of text within the frame, set this to center
                self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                //the horizontal alignment of the text
                self.myTextField.textAlignment = NSTextAlignmentLeft;
                //set the type of the keyboard to display
                self.myTextField.keyboardType = UIKeyboardTypeDecimalPad;
                //display the currency symbol in the left of the text field view
                self.myTextField.leftView = dollarSign;
                self.myTextField.leftViewMode = UITextFieldViewModeAlways;
                break;
            
            case 2:
                self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
                self.myTextField.textAlignment = NSTextAlignmentCenter;
                break;
            case 3:
                self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
                self.myTextField.textAlignment = NSTextAlignmentRight;
                self.myTextField.keyboardType = UIKeyboardTypeEmailAddress;
                break;
                
            default:
                self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
                self.myTextField.textAlignment = NSTextAlignmentCenter;
                break;
        }
        
        //display hint for the user data entry when the field is empty
        self.myTextField.placeholder = [NSString stringWithFormat:@"Enter data in field %i", i];
        //add tag to identify your text views
        self.myTextField.tag = i;
        //display the clear button on the text field
        self.myTextField.clearButtonMode = UITextFieldViewModeAlways;
        //change the return key text to "Done"
        self.myTextField.returnKeyType = UIReturnKeyDone;
        //set the delegate for the text field to the view controller so that it can listen for events
        self.myTextField.delegate = self;
        //add the text field to the current view
        [self.view addSubview:self.myTextField];
    }
    
}

//Asks the delegate if editing should begin in the specified text field.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    return YES;
}

//Tells the delegate that editing began for the specified text field.
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    NSInteger i = textField.tag;
    self.myLabel.text = [NSString stringWithFormat:@"Begin editing Text field %i", i];
    
}

//Asks the delegate if editing should stop in the specified text field.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    
    return YES;
}

//Tells the delegate that editing stopped for the specified text field.
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    NSInteger i = textField.tag;
    self.myLabel.text = [NSString stringWithFormat:@"Editing done for Text field %i", i];
    
}


//Asks the delegate if the specified text should be changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string{
    
    //get the current data strsing inside the text field
    NSString *myTextData = [textField.text stringByReplacingCharactersInRange:range
                                                                   withString:string];
    NSLog(@"Current data in text field is %@", myTextData);
    NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

    NSInteger i = textField.tag;
    switch (i) {
            
        case 1:
            //first field should only have numeric data otherwise don't allow change
            if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {
                return NO;
            }
            break;
            
        default:
            //don't allow more than 15 characters
            if ([myTextData length] > 15) {
                return NO;
            }
            break;
    }
    
    //set the display label value with the current data in the text field
    self.myLabel.text = [NSString stringWithFormat:@"Data: %@", myTextData];
    return YES;
}

//Asks the delegate if the text field’s current contents should be removed.
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    
    NSInteger i = textField.tag;
    NSLog(@"Text field %i just got cleared", i);
    return YES;
    
}

//Asks the delegate if the text field should process the pressing of the return button.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    //Notifies the receiver that it has been asked to relinquish
    //its status as first responder in its window.
    [textField resignFirstResponder];
    return YES;
}



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

@end

Reference

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.