ios - 将 UITextfield 设置为格式类型

标签 ios swift string replace uitextfield

我正在寻找一种简单的方法,将特定的 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/

相关文章:

swift - 没有这样的模块

python - 2020 年 Google 编程挑战题 : Unspecified Words

ios - 字体大小和类型不适用于 CATextLayer

ios - 按下安装后 iOS 配置文件返回什么类型的响应

ios - 如何处理由 viewWillTransitionToSize 函数旋转的 UIPageViewController VC?

下载 Alamofire 后快速保存文件

ios - 以编程方式添加 GADBannerView

ios - 找不到已创建的仅查看 Firebase 项目的 "Add App"按钮

c++ - 如何在 C++ 中获取所有可能的 n 个字符的字符串?

c# - 在 C# 中使用 Newtonsoft.Json.Linq 查询 JSON 操作日期字符串