Text Field With Number In iPhone

In this example we will see how to enter limited number in the TextField. So let see how it will worked.

Step 1: Open the Xcode, Create a new project using View Base application. Give the application “TextFieldWithNumber”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: Expand classes and notice Interface Builder created the ViewController class for you. Expand Resources and notice
the template generated a separate nib, TextFieldWithNumber.xib for the TextFieldWithNumber application.

Step 4: Open the TextFieldWithNumberViewController.h file and make the following changes:

 

#import <uikit/UIKit.h>
@interface TextFieldWithNumberViewController : UIViewController < UITextFieldDelegate > {
IBOutlet UITextField *text;
}
@property (nonatomic ,retain) IBOutlet UITextField *text;
@end

 

 

Step 5: Double click the TextFieldWithNumber.xib file and open it to the interface builder. First drag the TextField from the
library and place it to the view window. Select theTextField and bring up Connection Inspector, connect delegate to the File’s Owner icon and connect File’s Owner icon to the textfield and select text. Now save the .xib file, close it and go back to the Xcode.

Step 6: Open the TextFieldWithNumberViewController.m file and make the following changes:

 

#import "TextFieldWithNumberViewController.h"
@implementation TextFieldWithNumberViewController
@synthesize text;
- (void)viewDidLoad {
text.delegate = self;
[super viewDidLoad];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([newString length] > 8)
{
UIAlertView *obj_AlertView=[[UIAlertView alloc]initWithTitle:@""
message:@"Enter 8 digit only"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[obj_AlertView show];
[obj_AlertView release];
return !([newString length] > 8);
}
}
-(void)touchesBegan :(NSSet *)touches withEvent:(UIEvent *)event
{
[text resignFirstResponder];
[super touchesBegan:touches withEvent:event];
}
- (void)viewDidUnload {
}
@end

 

 

Step 7: Now compile and run the application on the Simulator.

You Can Download SourceCode from here