Tuesday, 15 March 2011

uitextfield - Detect backspace press in iOS -



uitextfield - Detect backspace press in iOS -

i trying validate 10 digit phone number entered in uitextfield. need number in format xxx-xxx-xxxx. not want user delete - symbol.

i tried using various approaches mentioned here: detect backspace in uitextfield, none of them seems work.

my current approach is:

- (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string { if (range.location == 12) { uialertview *alert =[[uialertview alloc]initwithtitle:@"invalid input" message:@"phone number can contain 10 digits." delegate:self cancelbuttontitle:@"ok" otherbuttontitles:nil]; [alert show]; [testtextfield resignfirstresponder]; homecoming no; } if (range.length == 0 && [blockedcharacters characterismember:[string characteratindex:0]]) { uialertview *alert =[[uialertview alloc]initwithtitle:@"invalid input" message:@"please come in numbers.\ntry again." delegate:self cancelbuttontitle:@"ok" otherbuttontitles:nil]; [alert show]; homecoming no; } if (range.length == 0 && (range.location == 3 || range.location == 7)) { textfield.text = [nsstring stringwithformat:@"%@-%@", textfield.text, string]; homecoming no; } if (range.length == 1 && (range.location == 4 || range.location == 8)) { range.location--; range.length = 2; textfield.text = [textfield.text stringbyreplacingcharactersinrange:range withstring:@""]; homecoming no; } homecoming yes; }

any thoughts on this?

thank much.

i faced similar problem this:

i know need - within numbers xxx-xxx-xxxx.

this how tackled it:

-(void)textfielddidendediting:(uitextfield *)textfield{ if (self.tf == textfield) { nsmutablestring *stringtf = [nsmutablestring stringwithstring:self.tf.text]; [stringtf insertstring:@"-" atindex:2]; [stringtf insertstring:@"-" atindex:5]; tf.text = stringdid; } }

so 1 time user done editing number, add together - them.

ios uitextfield

No comments:

Post a Comment