ios - 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
}
解决方案
在这种格式(#) #### #####
中,只使用了两个空格。因此,您可以在特定索引处插入空间,而无需像这样的 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
}
推荐阅读
- c# - Linq-to-SQL 谓词 VS UNION
- c - 结构外的指针和结构内的指针指向同一个数组并具有不同的存储地址
- python - 如果需要,列表理解中的索引问题
- http - 使用http post方法flutter时出错
- c++ - reinterpret_cast 意外地将类型从 `const float *` 更改为 `float`
- react-native - 如何在 mac 上卸载 react-native-cli?
- android - 是否可以同时使用 MIC、CAMCORDER 和加速度计进行录制?
- excel - 如何以编程方式在 Excel VBA 中移动或调整验证消息框的大小
- ldap - Spring Data LDAP 通常用于绑定身份验证吗?
- reactjs - 如何通过故事书传递我的组件主题?