首页 > 解决方案 > UitextFiled 的首字母必须为 0,格式类似于 (0) 1234 56789

问题描述

我正在使用电话号码 texfield,现在我将这种格式用于 texfield (#) #### #####,现在的问题是我希望第一个字符 0 作为必填项,例如 (0) 1234 56789,所以用户输入任何第一个字符必须输入0,它的不重复问题号格式不同

这是我的代码,但它不起作用

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if oldText.count > 15 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    let newText = String(stride(from: 0, to: oldText.count, by: 3).map {
        let sIndex = String.Index(encodedOffset: $0)
        let eIndex = oldText.index(sIndex, offsetBy: 3, limitedBy: oldText.endIndex) ?? oldText.endIndex
        return String(oldText[sIndex..<eIndex])
        }.joined(separator: " "))
    textField.text = newText
    return false
}

标签: iosswiftiphoneuitextfield

解决方案


在这种格式(#) #### #####中,只使用了两个空格。因此,您可以在特定索引处插入空间,而无需像这样的 for 循环

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var oldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    if oldText.count > 14 { return false }
    oldText = oldText.replacingOccurrences(of: "(0)", with: "").replacingOccurrences(of: " ", with: "")
    if !oldText.isEmpty {
        oldText = "(0)" + oldText
    }
    if oldText.count > 3 { 
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 3))
    }
    if oldText.count > 8 {
        oldText.insert(" ", at: oldText.index(oldText.startIndex, offsetBy: 8))
    }
    textField.text = oldText
    return false
}

推荐阅读