• Home
  • MAD
    • IOS Series
    • Android Series
    • Flutter Series
    • Xamarin Series
  • Concept Series
    • Software Design
    • Software Arch
    • GIT & Github
    • System Design
    • Cloud
    • Database Integration
    • Push Notification
    • API Integration
    • Cocoa PODS
  • DSA
  • Interview
  • Tips&Tricks
  • YT
  • Home
  • MAD
    • IOS Series
    • Android Series
    • Flutter Series
    • Xamarin Series
  • Concept Series
    • Software Design
    • Software Arch
    • GIT & Github
    • System Design
    • Cloud
    • Database Integration
    • Push Notification
    • API Integration
    • Cocoa PODS
  • DSA
  • Interview
  • Tips&Tricks
  • YT
  • #News
  • #APPS
  • #Events
    • #WWDC
    • #I/O
    • #Ignite
  • #Let’s Talk

MyCodeTips mycodetips-newlogocopy1

  • Home
  • MAD
    • IOS Series
    • Android Series
    • Flutter Series
    • Xamarin Series
  • Concept Series
    • Software Design
    • Software Arch
    • GIT & Github
    • System Design
    • Cloud
    • Database Integration
    • Push Notification
    • API Integration
    • Cocoa PODS
  • DSA
  • Interview
  • Tips&Tricks
  • YT
IOS

How to Create UITextField programmatically in IOS

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.

  • 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

Interface file for the view controller – UITextFieldViewController.h

#import <UIKit/UIKit.h>

@interface UITextFieldViewController : UIViewController 

@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 = @“Mycodetips…”;
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
Liked it? Take a second to support Ranjan on Patreon!
become a patron button
  • Click to share on Reddit (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • More
  • Click to share on Pocket (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
Written by Ranjan - 3784 Views
AUTHOR
Ranjan

Namaste, My name is Ranjan, I am a graduate from NIT Rourkela. This website is basically about of what i learnt from my years of experience as a software engineer on software development specifically on mobile application development, design patterns/architectures, its changing scenarios, security, troubleshooting, tools, tips&tricks and many more.

Next Post
Previous Post

Support us

mycodetips
mycodetips

Follow us @ LinkedIn 2850+

Subscribe for updates

Join 8,213 other subscribers

Latest Posts

  • YT-Featured-solidprinciples
    SOLID Principles of Software Design
  • IOS 16 Features
    Latest features in IOS 16
  • r-language
    How can R language be used for data analysis?
  • wordpress-coding-blog
    Guide To WordPress Coding Standards
  • YT-Featured-Algorithm
    What is Algorithm?
  • Frameworks of IOS
    Frameworks of IOS – Part ( I )
  • NSFileManager or NSPathUtilities
    NSFileManager or NSPathUtilities in Objective-C
  • Passing data between view controllers in Objective-C
    Passing data between view controllers in Objective-C
  • structures-classes-enum
    Structures and Classes in swift !
  • control-system-swift
    Control Flow in Swift
whiteboard

Whiteboard(PRO)

whiteboard

Whiteboard(lite)

alphabets

Kids Alphabet

techlynk

Techlynk

techbyte

Do2Day

techbyte

Techbyte

  • #about
  • #myapps
  • #contact
  • #privacy
  • #Advertise
  • #myQuestions

Android Android Studio API APP Programming Apps blogging CSS DATABASE dsa Features HTML HTML5 installation Interview Questions IOS iPhone javascript Mac objective-c OS Programming quicktips SDK SEO SQL swift Tips & Tricks Tools UI Web Wordpress Xcode

  • SOLID Principles of Software Design
  • Latest features in IOS 16
  • How can R language be used for data analysis?
  • Guide To WordPress Coding Standards
  • What is Algorithm?

©mycodetips.com