Ios Swift文本字段输入hh:mm作为持续时间

Ios Swift文本字段输入hh:mm作为持续时间,ios,swift,Ios,Swift,将textField委托方法用于: func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { switch textField { // allow only numbers case picTextField, sicTextField, p

将textField委托方法用于:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField {
            // allow only numbers
        case picTextField, sicTextField, pax1TextField, pax2TextField, pax3TextField, pax4TextField, lhCargoTextField, aftCargoTextField, rhCargoTextField, basketTextField, hookTextField,poleTextField, fuelTextField:
            let s = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
            guard !s.isEmpty else { return true }
            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .none
            return numberFormatter.number(from: s)?.intValue != nil
            // allow max 4 characters
        case departureTextField, destinationTextField, alternateTextField:
            let maxLength = 4
            let currentString: NSString = (textField.text ?? "") as NSString
            let newString: NSString =
                currentString.replacingCharacters(in: range, with: string) as NSString
            return newString.length <= maxLength
            // time formatting
        case tripTimeTextField:
                    default:
            return true
        }
func textField(textField:UITextField,shouldChangeCharacters范围:NSRange,replacementString:string)->Bool{
开关文本字段{
//只允许数字
案例PictTextField、sicTextField、pax1TextField、pax2TextField、pax3TextField、pax4TextField、lhCargoTextField、aftCargoTextField、rhCargoTextField、basketTextField、hookTextField、poleTextField、fuelTextField:
设s=NSString(string:textField.text???).replacingCharacters(in:range,with:string)
卫兵!s.isEmpty else{返回true}
设numberFormatter=numberFormatter()
numberFormatter.numberStyle=.none
返回numberFormatter.number(from:s)?.intValue!=nil
//允许最多4个字符
案例部门文本字段、destinationTextField、alternateTextField:
设maxLength=4
将currentString:NSString=(textField.text???)设为NSString
让新闻字符串:NSString=
currentString.replacingCharacters(在:范围内,带:字符串)作为NSString

return newString.length这是一个此类验证的愚蠢实现,可以根据您的用例进一步细化

func isValidHHMM(输入:字符串)->Bool{
让comps=input.components(以“:”分隔)
设hhComp=comps.first??“”
如果hhComp.count>2{
返回错误
}
设hh=Int(hhComp)??0
设hhValid=(hh<24)
防护罩组件计数==2其他{
返回hhValid
}
设mmComp=comps.last??“”
如果mmComp.count>2{
返回错误
}
设mm=Int(mmComp)??0
设mmValid=(mm<60)
返回(hhValid&&mmValid)
}