swift输入手机号码344格式

597 阅读1分钟

记录开发过程中常用功能,方便日后直接使用。😀

手机号码格式为344样式

public extension String {


  // 判断手机号是否合法 只判断是否是1开头
    func isTelNumber() -> Bool {
        if count == 0 || count != 11 {
            return false
        }
        let first: String = subString(start: 0, length: 1)
        return first == "1"
    }


      /**
     * 手机号格式化成3位4位4位的样式
     **/
    public func formatMobileWith344() -> String {
        if length != 11 {
            return self
        }
        let first: String = subString(start: 0, length: 3)
        let second: String = subString(start: 3, length: 4)
        let third: String = subString(start: 7, length: 4)
        return first + " " + second + " " + third
    }
}

手机号码输入时自动344样式

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if phoneTextField == textField {
            MobileFormat.phoneFormat(textField)
            let text = textField.text ?? ""
            if text.count >= 13 && string.count > 0 {
                return false
            }
        }
        return true
    }
class MobileFormat {
    static func phoneFormat(_ textField: UITextField) {
        let text = textField.text ?? ""

//        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 = MobileFormat.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)
        } // 设置光标位置
    }

    static 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
    }
}