Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在UITextField中从左到右实现货币/燃油价格格式(0,00)?_Ios_Swift_Uitextfield_Uitextfielddelegate - Fatal编程技术网

Ios 如何在UITextField中从左到右实现货币/燃油价格格式(0,00)?

Ios 如何在UITextField中从左到右实现货币/燃油价格格式(0,00)?,ios,swift,uitextfield,uitextfielddelegate,Ios,Swift,Uitextfield,Uitextfielddelegate,我目前正在开发一个应用程序,用户需要输入0,00格式的燃油价格,其中第一位数字后显示逗号,并且仅限于输入3位数字。 有人有解决方案吗?在UIViewController类中添加以下objc函数: @objc func format_textfield(_ sender:UITextField){ var str:String = sender.text! if str.count>0 && Array(str)[0] == ","{

我目前正在开发一个应用程序,用户需要输入0,00格式的燃油价格,其中第一位数字后显示逗号,并且仅限于输入3位数字。
有人有解决方案吗?

UIViewController
类中添加以下
objc
函数:

@objc func format_textfield(_ sender:UITextField){
    var str:String = sender.text!
    if str.count>0 && Array(str)[0] == ","{
        sender.text = String(str.suffix(from: str.index(str.startIndex,offsetBy: 1)))
        str = sender.text!
    }
    if str.count > 4 {
        sender.text = String(str.prefix(4))
    }else if str.count > 1 && Array(str)[1] != ","{
        sender.text = String(str[..<str.index(str.startIndex, offsetBy: 1)])+","+String(str[str.index(str.startIndex, offsetBy: 1)...])
    }
}

伟大的!很好的解决方案,但只有一件事,当我想删除时,我不能删除所有字符,例如我发短信1,99,但当我用数字键盘删除时,它保留在1,你能检查一下原因吗?给我几分钟,我会用更好的解决方案编辑我的答案:)好的,很高兴听到:)完成!它仍然可以改进,但我认为它已经足够好了。也许你可以做些改进。需要改进的地方:当你删除第一个数字时,文本光标会移到右边。效果很好,我很欣赏:)
textField.addTarget(self, action: #selector(format_textfield(_:)), for: .editingChanged)