ios - 如何限制 HH :MM:SS Formatter? 中的 textField 最大值

标签 ios swift uitextfield

我有 1 个 UITextTField,我只允许在这个“mm:ss”格式中输入数字,为此我使用了 StringFormatter

这是我的代码,适用于上述格式。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if textField.accessibilityHint == ExerciseParam.kTime {
        let lastText = (textField.text! as NSString).replacingCharacters(in: range, with: string) as String
        textField.text = lastText.format("nn:nn:nn", oldString: textField.text!)

        if lastText == "nn:nn:nn" {
            return false
        }
        else {

        }
        return false
    }
    else {
        return true
    }
}

我想做的事

我想要这样的东西。用户只能在 hh:mm:ss

中输入最大 60

有效输入 ==> ** **60:56:55

无效输入 ==> ** **66:56:80

如果我在文本字段中输入无效输入,那么它会自动变为 60:56:80 或者它会自动增加 MMHH 值,如 60:57: 20

我该怎么做。请给我建议。

谢谢

最佳答案

要限制键盘类型,您可以将文本字段 keyboardType 设置为 numberPad only

textField.keyboardType = .numberPad

这里是一个示例解决方案,如果你想支持24小时制的“HH”,需要添加更多的实现。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let lastText = (textField.text! as NSString).replacingCharacters(in: range, with: string) as String
    let formattedStr = lastText.format("nn:nn:nn", oldString: textField.text!)
    var rtn = formattedStr
    if formattedStr.count == 8 {
        guard let regex = try? NSRegularExpression(pattern: #"(\d{2})"#, options: [.caseInsensitive]) else {
            return false
        }
        let matches = regex.matches(in: formattedStr, options: [], range: NSMakeRange(0, formattedStr.count))
        var inc = false // do increment
        var ary: [String] = []
        for match in matches.reversed() {
            let str = String(formattedStr[Range(match.range, in: formattedStr)!])
            var num: Int = Int(str)!
            if inc {
                num += 1
            }
            inc = num > 60
            let aStr = inc ? String(format: "%02d", num - 60) : String(format: "%02d", num)
            ary.append(aStr)
        }
        print("ary: \(String(describing: ary))")
        rtn = ary.reversed().joined(separator: ":")
    }
    textField.text = rtn
    return rtn == "nn:nn:nn"
}

关于ios - 如何限制 HH :MM:SS Formatter? 中的 textField 最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56815413/

相关文章:

ios - 点击 subview Controller 或父 View Controller 时处理键盘关闭的替代方法?

ios - UIButton 被自动布局拉伸(stretch)

ios - 原生IOS设置远程视频描述发送参数失败

swift - 将搜索栏添加到表格 View

ios - 在 UITableViewCell 中有一个 UITextField

ios - 在Swift中按下UITextfield上的返回按钮时,如何添加空格?

ios - Swift Storyboard - 水平居中图标和多行文本

ios - 在 TableView 之外配置自定义 TableViewCell?

ios - 更改 subview 的高度后调整 super View 的大小 - 没有自动布局

ios - 在 UI ImageView 中检索和显示保存的图像(文档文件夹)