我正在寻找一种简单的方法,将特定的 UITextfield 实时格式化为一种类型。假设我有一个文本字段:taxNumber.text,我想设置一个类型,以便如果用户输入数字,它会在 3 个数字后自动添加一个“-”,并阻止用户在 6 个数字后输入。
谢谢!感谢所有帮助
最佳答案
如果您想要实现的唯一目的是仅允许文本字段中包含最多 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
}
在 3 位数字后添加 -
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
}
关于ios - 将 UITextfield 设置为格式类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49890495/