UITextField电话号码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UITextField电话号码相关的知识,希望对你有一定的参考价值。
我想知道如何格式化我用于电话号码的textField(例如iPhone上的“添加新联系人”页面。当我输入新的手机时,例如1236890987,它将其格式化为(123 )689-0987。)我已经将键盘设置为数字键盘。
答案
这是我的解决方案......效果很好!实时格式化电话号码。注意:这适用于10位数的电话号码。目前它自动格式化它像(xxx)xxx-xxxx ..调整到你心中的喜悦。
首先在shouldChangeCharactersInRange
中,您要收集电话文本字段的整个字符串,并将其传递给验证/格式化功能。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* totalString = [NSString stringWithFormat:@"%@%@",textField.text,string];
// if it's the phone number textfield format it.
if(textField.tag==102 ) {
if (range.length == 1) {
// Delete button was hit.. so tell the method to delete the last char.
textField.text = [self formatPhoneNumber:totalString deleteLastChar:YES];
} else {
textField.text = [self formatPhoneNumber:totalString deleteLastChar:NO ];
}
return false;
}
return YES;
}
这是电话号码格式化的地方。正则表达式可能会被清理一下。但我已经测试了这段代码一段时间,似乎已经通过了所有的钟声。请注意,我们还使用此功能删除电话号码中的号码。这里工作更容易,因为我们已经删除了所有其他非数字。
-(NSString*) formatPhoneNumber:(NSString*) simpleNumber deleteLastChar:(BOOL)deleteLastChar {
if(simpleNumber.length==0) return @"";
// use regex to remove non-digits(including spaces) so we are left with just the numbers
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\s-\(\)]" options:NSRegularExpressionCaseInsensitive error:&error];
simpleNumber = [regex stringByReplacingMatchesInString:simpleNumber options:0 range:NSMakeRange(0, [simpleNumber length]) withTemplate:@""];
// check if the number is to long
if(simpleNumber.length>10) {
// remove last extra chars.
simpleNumber = [simpleNumber substringToIndex:10];
}
if(deleteLastChar) {
// should we delete the last digit?
simpleNumber = [simpleNumber substringToIndex:[simpleNumber length] - 1];
}
// 123 456 7890
// format the number.. if it's less then 7 digits.. then use this regex.
if(simpleNumber.length<7)
simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\d{3})(\d+)"
withString:@"($1) $2"
options:NSRegularExpressionSearch
range:NSMakeRange(0, [simpleNumber length])];
else // else do this one..
simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\d{3})(\d{3})(\d+)"
withString:@"($1) $2-$3"
options:NSRegularExpressionSearch
range:NSMakeRange(0, [simpleNumber length])];
return simpleNumber;
}
另一答案
您可以添加电话号码,如000-000-0000(10位数)。请参考此代码。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField==Phone_TXT)
{
if (range.location == 12)
{
return NO;
}
// Backspace
if ([string length] == 0)
return YES;
if ((range.location == 3) || (range.location == 7))
{
NSString *str = [NSString stringWithFormat:@"%@-",textField.text];
textField.text = str;
}
return YES;
}
}
另一答案
我的+ X(XXX)XXX-XXXX格式的解决方案。 (迅速)
func textFieldDidBeginEditing(textField: UITextField) {
if (textField == self.mobileField) {
textField.text = "+"
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if (textField == self.mobileField) {
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
if (newString.characters.count < textField.text?.characters.count && newString.characters.count >= 1) {
return true // return true for backspace to work
} else if (newString.characters.count < 1) {
return false; // deleting "+" makes no sence
}
if (newString.characters.count > 17 ) {
return false;
}
let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let decimalString = components.joinWithSeparator("") as NSString
let length = decimalString.length
var index = 0
let formattedString = NSMutableString()
formattedString.appendString("+")
if (length >= 1) {
let countryCode = decimalString.substringWithRange(NSMakeRange(0, 1))
formattedString.appendString(countryCode)
index += 1
}
if (length > 1) {
var rangeLength = 3
if (length < 4) {
rangeLength = length - 1
}
let operatorCode = decimalString.substringWithRange(NSMakeRange(1, rangeLength))
formattedString.appendFormat(" (%@) ", operatorCode)
index += operatorCode.characters.count
}
if (length > 4) {
var rangeLength = 3
if (length < 7) {
rangeLength = length - 4
}
let prefix = decimalString.substringWithRange(NSMakeRange(4, rangeLength))
formattedString.appendFormat("%@-", prefix)
index += prefix.characters.count
}
if (index < length) {
let remainder = decimalString.substringFromIndex(index)
formattedString.appendString(remainder)
}
textField.text = formattedString as String
if (newString.characters.count == 17) {
textField.resignFirstResponder()
}
return false
}
return true
}
另一答案
Swift 4(没有NSString)
格式+ X(XXX)XXX-XXXX或+ X(XXX)XXX-XX-XX更新并稍微更新
class ViewController: UIViewController, UITextFieldDelegate {
var myPhoneNumber = String()
@IBOutlet weak var phoneTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
phoneTextField.delegate = self
phoneTextField.keyboardType = .phonePad
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField == self.phoneTextField) && textField.text == ""{
textField.text = "+7(" //your country code default
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == phoneTextField {
let res = phoneMask(phoneTextField: phoneTextField, textField: textField, range, string)
myPhoneNumber = res.phoneNumber != "" ? "+(res.phoneNumber)" : ""
print("Phone - (myPhoneNumber) MaskPhone=(res.maskPhoneNumber)")
if (res.phoneNumber.count == 11) || (res.phoneNumber.count == 0) {
//phone number entered or completely cleared
print("EDIT END: Phone = (myPhoneNumber) MaskPhone = (res.maskPhoneNumber)")
}
return res.result
}
return true
}
}
extension UITextFieldDelegate {
func phoneMask(phoneTextField: UITextField, textField: UITextField, _ range: NSRange, _ string: String) -> (result: Bool, phoneNumber: String, maskPhoneNumber: String) {
let oldString = textField.text!
let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!, with: string)
//in numString only Numeric characters
let components = newString.components(separatedBy: CharacterSet.decimalDigits.inverted)
let numString = com以上是关于UITextField电话号码的主要内容,如果未能解决你的问题,请参考以下文章
UITextField 中的 C# Monotouch 电话号码格式
不允许用户输入数字1作为UITextField中的第一个数字