今天在項(xiàng)目遇到輸入手機(jī)號(hào)自動(dòng)輸入空格的樣式如136 3961 1234
的樣式,自己寫的方法船侧,以供參考。
思路:
利用UITextField的代理方法textFieldDidEditing:該方法實(shí)現(xiàn)輸入框文字變動(dòng)時(shí)的監(jiān)聽:,然后利用字符串的分割拼接來(lái)實(shí)現(xiàn)
實(shí)現(xiàn)方法:
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便可實(shí)現(xiàn)實(shí)現(xiàn)輸入手機(jī)號(hào)時(shí)自動(dòng)添加空格,
//備注:當(dāng)?shù)降谒奈换虻诰盼粫r(shí),如果此時(shí)是正在輸入,則自動(dòng)增加空格,如果正在刪除,則自動(dòng)刪除空格!!!
//當(dāng)?shù)降?3位時(shí),截取前面的13位字符串,收起鍵盤
//若想要獲取輸入的手機(jī),需要先刪除空格;
NSString *textFieldStr =[self.textField.text stringByReplacingOccurrencesOfString:@" "withString:@""];