Sometimes the project requires the text box can only enter numbers, such as: Price, kilometer, cost, etc., the general text box does not restrict the format of input, this time can only force the input format to restrict the entry box, the code is as follows:
#import "ViewController.h"
@interface Viewcontroller () <uitextfielddelegate>{
Uitextfield *numtextfield;
}
@end
@implementation Viewcontroller
-(void) viewdidload {
[super viewdidload];
numtextfield = [[Uitextfield alloc] Initwithframe:cgrectmake (60, 80, 100, 40)];
numtextfield.layer.bordercolor = [[Uicolor Graycolor]cgcolor];
numtextfield.layer.borderwidth = 1.0f;
numtextfield.delegate = self;
numtextfield.textalignment = Nstextalignmentcenter;
[self.view Addsubview:numtextfield];
}
#pragma mark-uitextfield Limit input numbers
-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) String {
if (TextField = = Numtextfield) {
return [self validatenumber:string];
}
return YES;
}
#pragma mark-Verify if it is a pure number
-(BOOL) ValidateNumber: (nsstring*) Number {
BOOL res = YES;
Nscharacterset *tmpset = [Nscharacterset charactersetwithcharactersinstring:@ "0123456789"];
int i = 0;
while (I < number.length) {
NSString * string = [number Substringwithrange:nsmakerange (I, 1)];
Nsrange range = [string Rangeofcharacterfromset:tmpset];
if (Range.length = = 0) {
res = NO;
NSLog (@ "Please enter number");
Break
}
i++;
}
return res;
}
-(void) didreceivememorywarning {
[Super didreceivememorywarning];
Dispose of any resources the can be recreated.
}
@end
Note: When writing the article, suddenly thought can set the keyboard style for the digital form (uikeyboardtypenumberpad), such words should also be limited, through the simulator debugging, set the keyboard style does not work, because the keyboard can be used on the computer to enter Chinese characters or letters, Do not know whether the real machine can, interested in the test can be on the real machine.
IOS Uitextfield Limit input numbers