Ios 将文本字段中的逗号替换为十进制分隔符

Ios 将文本字段中的逗号替换为十进制分隔符,ios,swift,uitextfield,Ios,Swift,Uitextfield,有人能告诉我如何用文本字段中的替换,分隔符吗?用户可以输入类似5,6的内容,但当他按下按钮时,我想将他输入的数据作为5,6提交到5.6,因为否则不会进行十进制计算 我有这个扩展字符串文件,但似乎只限于文本中的一个逗号和逗号后的两个小数,而不是将,转换为 extension String { private static let decimalFormatter:NumberFormatter = { let formatter = NumberFormatter() forma

有人能告诉我如何用文本字段中的
替换
分隔符吗?用户可以输入类似
5,6
的内容,但当他按下按钮时,我想将他输入的数据作为
5,6
提交到
5.6
,因为否则不会进行十进制计算

我有这个扩展字符串文件,但似乎只限于文本中的一个逗号和逗号后的两个小数,而不是将
转换为

extension String {

private static let decimalFormatter:NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.allowsFloats = true
    return formatter
}()

private var decimalSeparator:String{
    return String.decimalFormatter.decimalSeparator ?? "."
}


func isValidDecimal(maximumFractionDigits:Int)->Bool{

    guard self.isEmpty == false else {
        return true
    }

    // Check if valid decimal
    if let _ = String.decimalFormatter.number(from: self){

        // Get fraction digits part using separator
        let numberComponents = self.components(separatedBy: decimalSeparator)
        let fractionDigits = numberComponents.count == 2 ? numberComponents.last ?? "" : ""
        return fractionDigits.characters.count <= maximumFractionDigits
    }

    return false
}

var doubleValue: Double {
    let nf = NumberFormatter()
    nf.decimalSeparator = "."
    if let result = nf.number(from: self) {
        return result.doubleValue
    } else {
        nf.decimalSeparator = ","
        if let result = nf.number(from: self) {
            return result.doubleValue
        }
    }
    return 0
}
}
扩展字符串{
私有静态let decimalFormatter:NumberFormatter={
let formatter=NumberFormatter()
formatter.allowsFloats=true
返回格式化程序
}()
私有变量小数分隔符:字符串{
返回字符串.decimalFormatter.decimalSeparator??”
}
func isValidDecimal(最大分数位数:Int)->Bool{
guard self.isEmpty==false else{
返回真值
}
//检查小数点是否有效
如果let=String.decimalFormatter.number(from:self){
//使用分隔符获取零件的分数位数
设numberComponents=self.components(分隔符:小数分隔符)
让fractionDigits=numberComponents.count==2?numberComponents.last??“”

单击按钮“在下面写入替换字符串的代码”时返回fractionDigits.characters.count

let strReplace = txtField.text.replacingOccurrences(of: ",", with: ".", options: .literal, range: nil)// change "txtField" your textfield's object
print(\(strReplace))

您应该为uitextfield添加委托方法

class ViewController: UIViewController, UITextFieldDelegate
然后在viewdidload中添加self

 override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self;
    // Do any additional setup after loading the view, typically from a nib.
}
然后在可以更改字符的函数中添加以下函数

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) {

 print("While entering the characters this method gets called")
 let strReplace = txtField.text.replacingOccurrences(of: ",", with: ".", options: .literal, range: nil)
// change "txtField" your textfield's object
 print(\(strReplace))

}
现在您可以获得替换字符串以及当前的文本字段文本