我正在使用电话号码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
}
答案 0 :(得分:1)
在这种格式(#) #### #####
中,仅使用两个空格。因此,您可以在没有这样的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
}