Sometimes in the project requires a text box can only enter numbers, such as: Price, mileage, fees, etc., the general text box does not limit the format of the input, this time can only be forced to restrict the input box input format, 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's 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 a number");
Break
}
i++;
}
return res;
}
-(void) didreceivememorywarning {
[Super didreceivememorywarning];
Dispose of any of the can is recreated.
}
@end
Note: When writing an article, it suddenly occurred to me that you can set the keyboard style as a digital form (UIKEYBOARDTYPENUMBERPAD), which should also be limited, through the simulator debugging, set the keyboard style does not work, because the keyboard on the computer can enter Chinese characters or letters, Do not know whether the real machine can be interested in the real machine can be tested.