将 UITextfield 设置为格式类型
set UITextfield to format type
我正在寻找一种将特定 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
}
我正在寻找一种将特定 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
}