iOS ~ 格式化电话号码 (3 4 4 位空格分割)

在文本框输入电话号码时,按照 3 4 4 的格式动态显示(如 130 1234 1234)

首先添加上UITextField的代理 UITextFieldDelegate

swift:
    private var phoneContent = ""
    private var previousSelection = UITextRange()
    
    private lazy var textFieldPhone: UITextField = {
        let newTextField = UITextField()
        newTextField.delegate = self
        newTextField.addTarget(self, action: #selector(textFieldChange(_:)), for: .editingChanged)
         
        return newTextField
    }()
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textFieldPhone == textField {
            phoneContent = textField.text ?? ""
            if phoneContent.count >= 13 && string.count > 0 {
                print("手机号码为11位")
                return false
            }
            previousSelection = textField.selectedTextRange ?? UITextRange()
        } 
        return true
    }
@objc func textFieldChange(_ textField: UITextField) {
        let text = textField.text ?? ""
        if textFieldPhone == textField {
            var editFlag = false //是否执行删除操作
            if text.count < phoneContent.count {
                editFlag = true
            }
            var targetPosition = 0 //光标位置
            if let start = textField.selectedTextRange?.start {
                targetPosition = textField.offset(from: textField.beginningOfDocument, to: start)
            }
            textField.text = isPhone(text)
            
            var currentPosition = targetPosition
            if editFlag {
                if currentPosition == 4 || currentPosition == 9 {
                    currentPosition -= 1
                }
            } else {
                if targetPosition == 4 || targetPosition == 9 {
                    currentPosition += 1
                }
            }
            let nowPosition = textField.position(from: textField.beginningOfDocument, offset: currentPosition)

            if let beginPosition = nowPosition {
                textField.selectedTextRange = textField.textRange(from: beginPosition, to: beginPosition)
            } // 设置光标位置
        } 
    }
///手机号码分割 3 4 4 
public func isPhone(_ str: String) -> String {
    var phone = str.replacingOccurrences(of: " ", with: "")
    switch phone.count {
    case 4...7:
        phone.insert(" ", at: phone.index(phone.startIndex, offsetBy: 3))
    case 8...11:
        phone.insert(" ", at: phone.index(phone.startIndex, offsetBy: 7))
        phone.insert(" ", at: phone.index(phone.startIndex, offsetBy: 3))
    default:
        break
    }
    return phone
}
Objective-C:
@property (nonatomic, strong) UITextField * textField; 

@property (nonatomic, strong) UITextRange * previousSelection;

@property (nonatomic, strong) NSString * phoneContent;


- (UITextField *)textField {
    if (_textField == nil) {
        UITextField * newTextField = [[UITextField alloc] init];
        newTextField.delegate = self; 
        [newTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
        
        _textField = newTextField;
    }
    return _textField;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (self.textField == textField) {
        self.phoneContent       = textField.text;
        if (self.phoneContent.length >= 13 && string.length > 0) {
            NSLog(@"手机号码为11位");
            return NO;
        }
        self.previousSelection  = textField.selectedTextRange;
    }
    return YES;
}

///输入判断
- (void)textFieldChange:(UITextField *)textField {
    NSString * currentText = textField.text;
    if (self.textField == textField) {
            //是否正在执行删除操作
            BOOL editFlag = NO;
            if (currentText.length < self.phoneContent.length) {
                editFlag = YES;
            } 
            //光标位置
            NSInteger targetPosition = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
            textField.text = [currentText isPhone];
            
            NSInteger currentPosition = targetPosition;
            //删除
            if (editFlag) {
                if (currentPosition == 4 || currentPosition == 9) {
                    currentPosition -= 1;
                }
            } else {
                if (currentPosition == 4 || currentPosition == 9) {
                    currentPosition += 1;
                }
            }
            UITextPosition * nowPosition = [textField positionFromPosition:textField.beginningOfDocument offset:currentPosition];
            
            textField.selectedTextRange = [textField textRangeFromPosition:nowPosition toPosition:nowPosition]; 
    } 
}
NSString 扩展
- (NSString *)isPhone {
    NSString * str = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableString * phone = [NSMutableString stringWithString:str];
    if (phone.length <= 3) {
        
    } else if (phone.length <= 7) {
        [phone insertString:@" " atIndex:3];
    } else if (phone.length <= 11) {
        [phone insertString:@" " atIndex:7];
        [phone insertString:@" " atIndex:3];
    }
    return phone;
}

此处仅为笔记,为了防止以后再次写此功能。

你可能感兴趣的:(iOS ~ 格式化电话号码 (3 4 4 位空格分割))