first set Uitextfield's keyboard to number Pad in. xib, but the keyboard will be cut back to other keyboards when used to verify the content. Through the magic of Baidu I know the following methods to solve the problem:
First let. Xib's Viewcontroller implement Uitextfielddelegate and then associate with the control you want to validate.
The above is xib, if the code is set, do not consider or the part of the face
Then paste the following code into the class.
-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string { return [self validatenumber:string];} -(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; break; } i++; }
There is another way, I haven't tried this way, but I found it and shared it:
1. Define constants for use
#define NUMBERS @ "0123456789"
2. Do the following
-(BOOL) TextField: (uitextfield*) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( nsstring*) string{ Nscharacterset*cs; CS = [[nscharactersetcharactersetwithcharactersinstring:numbers] invertedset]; nsstring*filtered = [[string Componentsseparatedbycharactersinset:cs] componentsjoinedbystring:@ ""]; Boolbasictest = [string isequaltostring:filtered]; if (!basictest) { uialertview* alert = [[Uialertviewalloc] initwithtitle:@ "Prompt" message:@ "Please enter a number" delegate : nil cancelbuttontitle:@ "OK" Otherbuttontitles:nil]; [Alert show]; Returnno; } Returnyes;}
iOS settings TextField can only enter numbers for phone numbers