Ios 将UITextfield设置为格式类型
我正在寻找一种简单的方法,将特定UITextfield实时格式化为一种类型。假设我有一个textfield:taxNumber.text我想设置一个类型,这样如果用户键入数字,它会在3个数字后自动添加“-”,并阻止用户在6个数字后键入Ios 将UITextfield设置为格式类型,ios,swift,string,replace,uitextfield,Ios,Swift,String,Replace,Uitextfield,我正在寻找一种简单的方法,将特定UITextfield实时格式化为一种类型。假设我有一个textfield:taxNumber.text我想设置一个类型,这样如果用户键入数字,它会在3个数字后自动添加“-”,并阻止用户在6个数字后键入 塔克斯!感谢所有帮助如果您想要实现的唯一一件事是只允许文本字段中的数字最多有6位,并且在3位之后有一个-,您可以执行以下操作 设置UITextField myTextField.keyboardType = .numberPad //This will only
塔克斯!感谢所有帮助如果您想要实现的唯一一件事是只允许文本字段中的数字最多有6位,并且在3位之后有一个
-
,您可以执行以下操作
设置UITextField
myTextField.keyboardType = .numberPad
//This will only allow numbers to be entered
myTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
//This will call "textFieldDidChange" method every time there is an edit
最多6个字符
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Only return true if there are less than six characters excluding the "-"
if textField.text!.replacingOccurrences(of: "-", with: "").count == 6 && string != "" {
return false
}
return true
}
func textFieldDidChange(_ textField: UITextField) {
var currentText = textField.text!.replacingOccurrences(of: "-", with: "")
if currentText.count >= 4 {
//Add "-" after three characters if there are four or more characters
currentText.insert("-", at: currentText.index(currentText.startIndex, offsetBy: 3))
}
textField.text = currentText
}
在3位数字后添加一个-
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Only return true if there are less than six characters excluding the "-"
if textField.text!.replacingOccurrences(of: "-", with: "").count == 6 && string != "" {
return false
}
return true
}
func textFieldDidChange(_ textField: UITextField) {
var currentText = textField.text!.replacingOccurrences(of: "-", with: "")
if currentText.count >= 4 {
//Add "-" after three characters if there are four or more characters
currentText.insert("-", at: currentText.index(currentText.startIndex, offsetBy: 3))
}
textField.text = currentText
}
具体来看,有大量的例子,类似的问题每天至少会被问一次。非常感谢!!很高兴能帮上忙,只有当我点击退格按钮时,它才会转到分隔符。如果需要的话,我想能够删除整数。我需要转换很多文本字段。这种方法也可以吗?@Stijnk008要删除整数,可以在编辑时将
UITextField
的clearButtonMode
设置为。这样,当编辑文本字段时,它将显示一个x
按钮来清除它。您还可以打开一个设置,一旦编辑开始,该设置将立即清除文本字段。如果需要转换多个文本字段,可以将UITextField
子类化为自定义文本字段