【发布时间】:2020-12-18 16:00:39
【问题描述】:
我正在为电话号码创建一个 TextField。 但是我有一些麻烦:我需要防止用户从任何地方编辑它,而不是字符串的末尾。
我尝试使用“Touch up Inside”重置插入符号,但它似乎对 TextField 禁用。
有没有办法限制插入符号的可能位置?
问题是它破坏了我的代码,它格式化了电话号码。如果您有任何其他好的方法来格式化它而不会出现这个问题(我需要字符串看起来完全像这样:+7 (123) 456-78-90,而不是任何其他方式),我会感谢您的帮助。
private static var prev_phone: String = ""
@IBAction func phoneFieldTextChanged(_ sender: Any){
if let phone = phone_field.text{
if(phone.count <= 4){
phone_field.text = "+7 ("
}
else{
if phone.count > RegistrationViewController.prev_phone.count{
if(phone.count == 7){
phone_field.text! += ") "
}
if(phone.count == 12){
phone_field.text! += "-"
}
if(phone.count == 15){
phone_field.text! += "-"
}
if(phone.count > 18){
phone_field.text = String(phone.prefix(18))
}
}
if phone.count < RegistrationViewController.prev_phone.count{
if(phone.count == 8){
phone_field.text! = String(phone.prefix(6))
}
if(phone.count == 12){
phone_field.text! = String(phone.prefix(11))
}
if(phone.count == 15){
phone_field.text! = String(phone.prefix(14))
}
if(phone.count > 18){
phone_field.text = String(phone.prefix(18))
}
}
}
}
else{
phone_field.text = "+7 ("
}
RegistrationViewController.prev_phone = phone_field.text!
}
【问题讨论】:
标签: ios swift string uitextfield string-formatting