UITextField for Phone Number

2020-01-24 10:54发布

I was wondering how I can format the textField that I'm using for a phone number (ie like the "Add New Contact" page on the iPhone. When I enter in a new mobile phone, ex. 1236890987 it formats it as (123) 689-0987.) I already have the keyboard set as the number pad.

24条回答
一纸荒年 Trace。
2楼-- · 2020-01-24 11:20

Here's how you can do it in Swift 4:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    if (textField == phoneTextField) {
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        let components = newString.components(separatedBy: NSCharacterSet.decimalDigits.inverted)

        let decimalString = components.joined(separator: "") as NSString
        let length = decimalString.length
        let hasLeadingOne = length > 0 && decimalString.hasPrefix("1")

        if length == 0 || (length > 10 && !hasLeadingOne) || length > 11 {
            let newLength = (textField.text! as NSString).length + (string as NSString).length - range.length as Int

            return (newLength > 10) ? false : true
        }
        var index = 0 as Int
        let formattedString = NSMutableString()

        if hasLeadingOne {
            formattedString.append("1 ")
            index += 1
        }
        if (length - index) > 3 {
            let areaCode = decimalString.substring(with: NSMakeRange(index, 3))
            formattedString.appendFormat("(%@)", areaCode)
            index += 3
        }
        if length - index > 3 {
            let prefix = decimalString.substring(with: NSMakeRange(index, 3))
            formattedString.appendFormat("%@-", prefix)
            index += 3
        }

        let remainder = decimalString.substring(from: index)
        formattedString.append(remainder)
        textField.text = formattedString as String
        return false
    }
    else {
        return true
    }
}
查看更多
ら.Afraid
3楼-- · 2020-01-24 11:22

You can call this method whenever you need to update your textField:

extension String {
    func applyPatternOnNumbers(pattern: String, replacmentCharacter: Character) -> String {
        var pureNumber = self.replacingOccurrences( of: "[^0-9]", with: "", options: .regularExpression)
        for index in 0 ..< pattern.count {
            guard index < pureNumber.count else { return pureNumber }
            let stringIndex = String.Index(encodedOffset: index)
            let patternCharacter = pattern[stringIndex]
            guard patternCharacter != replacmentCharacter else { continue }
            pureNumber.insert(patternCharacter, at: stringIndex)
        }
        return pureNumber
    }
}

Example:

 guard let text = textField.text else { return }
 textField.text = text.applyPatternOnNumbers(pattern: "+# (###) ###-####", replacmentCharacter: "#")
查看更多
不美不萌又怎样
4楼-- · 2020-01-24 11:22

This is my solution using Swift 4 to format a number of type (123) 689-0987

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let currentText:String = textField.text else {return true}
    if string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) != nil { return false }
    let newCount:Int = currentText.count + string.count - range.length
    let addingCharacter:Bool = range.length <= 0

    if(newCount == 1){
        textField.text = addingCharacter ? currentText + "(\(string)" : String(currentText.dropLast(2))
        return false
    }else if(newCount == 5){
        textField.text = addingCharacter ? currentText + ") \(string)" : String(currentText.dropLast(2))
        return false
    }else if(newCount == 10){
        textField.text = addingCharacter ? currentText + "-\(string)" : String(currentText.dropLast(2))
        return false
    }

    if(newCount > 14){
        return false
    }

    return true
}
查看更多
手持菜刀,她持情操
5楼-- · 2020-01-24 11:25

u have to do to this manually . take a notification of textField and check length of field text and format it according to country. if any problem let me know. I have done this

查看更多
家丑人穷心不美
6楼-- · 2020-01-24 11:27

You can add phone number like as 000-000-0000 (10- Digit). Please refer this code.

- (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;
    }
}
查看更多
甜甜的少女心
7楼-- · 2020-01-24 11:29
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSCharacterSet* validationSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSArray* components = [string componentsSeparatedByCharactersInSet:validationSet];

if ([components count] > 1) {
    return NO;
}

NSString* newString = [textField.text stringByReplacingCharactersInRange:range
                                                                 withString:string];

NSArray* validComponents = [newString componentsSeparatedByCharactersInSet:validationSet];

static const int localNumberMaxLength = 7;
static const int areaCodeMaxLength = 3;
static const int countryCodeMaxLength = 2;

newString = [validComponents componentsJoinedByString:@""];

if ([newString length] > localNumberMaxLength + areaCodeMaxLength + countryCodeMaxLength) {
    return NO;
}


NSLog(@"new string: %@", newString);

NSMutableString* resultString = [NSMutableString string];

NSInteger localNumberLength = MIN([newString length], localNumberMaxLength);

if (localNumberLength > 0) {
    NSString* number = [newString substringFromIndex:(int)[newString length] - localNumberLength];
    [resultString appendString:number];

    if ([resultString length] > 3) {
        [resultString insertString:@"-" atIndex:3];
    }
}

if ([newString length] > localNumberMaxLength) {
    NSInteger areaCodeLength = MIN((int)[newString length] - localNumberMaxLength, areaCodeMaxLength);
    NSRange areaRange = NSMakeRange((int)[newString length] - localNumberMaxLength - areaCodeLength, areaCodeLength);
    NSString* area = [newString substringWithRange:areaRange];

    area = [NSString stringWithFormat:@"(%@) ",area];

    [resultString insertString:area atIndex:0];
}

if ([newString length] > localNumberMaxLength + areaCodeMaxLength) {
    NSInteger countryCodeLength = MIN((int)[newString length] - localNumberMaxLength - areaCodeMaxLength, countryCodeMaxLength);
    NSRange countryCodeRange = NSMakeRange(0, countryCodeLength);
    NSString* countryCode = [newString substringWithRange:countryCodeRange];

    countryCode = [NSString stringWithFormat:@"+%@ ",countryCode];

    [resultString insertString:countryCode atIndex:0];
}

textField.text = resultString;
return NO;    

}

查看更多
登录 后发表回答