【IOS开发】UItextfield输入电话号码,自动调整格式
UItextfield中实现输入电话号码,自动按位置在加“—”效果。效果图如下。
核心代码:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (range.location == 13) { return NO; }else if (range.location == 8){ NSMutableString *str = [[NSMutableString alloc] initWithString:phoneField.text]; NSRange range = [str rangeOfString:@"-"]; if (range.location!=NSNotFound) { }else { [str insertString:@"-" atIndex:3]; [str insertString:@"-" atIndex:8]; phoneField.text = str; } return YES; }else if(range.location==9) { NSMutableString *str = [[NSMutableString alloc] initWithString:phoneField.text]; NSString *str1; str1 = [str stringByReplacingOccurrencesOfString:@"-"withString:@""]; phoneField.text = str1; return YES; }else { return YES; } }