【问题标题】:set UITextfield to format type将 UITextfield 设置为格式类型
【发布时间】:2018-04-18 03:03:08
【问题描述】:

我正在寻找一种将特定 UITextfield 实时格式化为类型的简单方法。假设我有一个文本字段:taxNumber.text 我想设置一个类型,以便如果用户输入数字,它会在 3 个数字后自动添加一个“-”,并阻止用户在 6 个数字后输入。

谢谢!感谢所有帮助

【问题讨论】:

标签: ios swift string replace uitextfield


【解决方案1】:

如果您想要实现的唯一目标是在文本字段中只允许最多 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
}

【讨论】:

  • 非常感谢!!
  • 很高兴为您提供帮助
  • 只有当我点击退格按钮时,它才会上升到分隔符。如果需要,我希望能够删除整个数字
  • 而且我需要转换很多文本字段,这种方法也可以吗?
  • @Stijnk008 要删除整个数字,您可以将UITextFieldclearButtonMode 设置为whileEditing。这样,在编辑文本字段时,它将显示一个x 按钮以将其清除。您还可以打开一个设置,该设置将在编辑开始后立即清除文本字段。如果您需要转换多个文本字段,您可以将UITextField 子类化为自定义文本字段
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多