在iOS 10 中,UITextField新增了textContentType字段,是UITextContentType类型,它是一个枚举,作用是可以指定输入框的类型,以便系统可以分析出用户的语义.
今天我们就主要研究下:UITextContentTypeTelephoneNumber 手机号码
效果如图所示
1. 首先,实现的第一步,我们需要监听指定输入框(UITextFieldDelegate无法完全实现此功能)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:) name:UITextFieldTextDidChangeNotification object:self.txtPhoneNumber];
2.设置输入框 textContentType = UITextContentTypeTelephoneNumber,keyboardType = UIKeyboardTypeNumbersAndPunctuation,并做好iOS10以下版本的兼容
if (@available(iOS 10.0, *)) {
self.txtPhoneNumber.textContentType = UITextContentTypeTelephoneNumber;
self.txtPhoneNumber.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
}else
{
self.txtPhoneNumber.keyboardType = UIKeyboardTypeNumberPad;
}
3.处理输入结果
#pragma mark - UITextFieldTextDidChangeNotification
-(void)textFieldEditChanged:(NSNotification *)obj
{
UITextField *textField = (UITextField *)obj.object;
NSString *toBeString = textField.text;
//兼容键盘QuickType Bar以+86开头的号码
toBeString = [toBeString stringByReplacingOccurrencesOfString:@"+" withString:@""];
//兼容英文键盘前后空格
toBeString = [toBeString stringByReplacingOccurrencesOfString:@" " withString:@""];
if (toBeString.length>0) {
if (![self isNumber:toBeString]) {
//兼容输入非数字时的处理 ,切去最后一位
toBeString = [toBeString substringToIndex:toBeString.length-1];
}
}
textField.text = toBeString;
//此处为处理键盘提示号码逻辑(如:8618000000000)及(如:+861800000000)
if (@available(iOS 10.0, *)) {
//兼容号码数字键盘
if (toBeString.length==13) {
NSString * startString = [toBeString substringToIndex:3];
if ([startString isEqualToString:@"861"]) {
//当字符串长度为13位,并以861开头时,截取86,余下则为11位手机号
textField.text = [toBeString substringFromIndex:2];
}
}
}
}
4.结合(UITextFieldDelegate)处理输入表情特殊字符逻辑
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([string isEqualToString:@"\n"]) {
[textField resignFirstResponder];
return NO;
}
if (textField == self.txtPhoneNumber) {
if ([self isContainsEmoji:string]) {
//禁输表情符号
return NO;
}
}
return YES;
}
总结:
此方式可实现获取键盘QuickType Bar所提示手机号码、屏蔽特殊字符、禁输Emoji表情,完美实现手机号的输入和快速键盘获取的功能,欢迎大家指正探讨
问题点:
只支持中国大陆的11位号码,其它国家和地区因国家码不同号码长度不同,暂不支持
源码在此* demo