今天在项目遇到输入手机号自动输入空格的样式如136 3961 1234
的样式,自己写的方法,以供参考。
思路:
利用UITextField的代理方法textFieldDidEditing:该方法实现输入框文字变动时的监听:,然后利用字符串的分割拼接来实现
实现方法:
UITextField代理方法中代码:
NSInteger i;//定义全局变量
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
i = 0;
[self.textField addTarget:self action:@selector(textFieldDidEditing:) forControlEvents:UIControlEventEditingChanged];
}
-(void)textFieldDidEditing:(UITextField *)textField{
if (textField == self.textField) {
if (textField.text.length > i) {
if (textField.text.length == 4 || textField.text.length == 9 ) {//输入
NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
[str insertString:@" " atIndex:(textField.text.length-1)];
textField.text = str;
}if (textField.text.length >= 13 ) {//输入完成
textField.text = [textField.text substringToIndex:13];
[textField resignFirstResponder];
}
i = textField.text.length;
}else if (textField.text.length < i){//删除
if (textField.text.length == 4 || textField.text.length == 9) {
textField.text = [NSString stringWithFormat:@"%@",textField.text];
textField.text = [textField.text substringToIndex:(textField.text.length-1)];
}
i = textField.text.length;
}
}
}
ok,上面demo便可实现实现输入手机号时自动添加空格,
//备注:当到第四位或第九位时,如果此时是正在输入,则自动增加空格,如果正在删除,则自动删除空格!!!
//当到第13位时,截取前面的13位字符串,收起键盘
//若想要获取输入的手机,需要先删除空格;
NSString *textFieldStr =[self.textField.text stringByReplacingOccurrencesOfString:@" "withString:@""];
网友评论