用TextField替换带小数分隔符的逗号

时间:2017-10-14 06:49:08

标签: ios swift uitextfield

有人可以告诉我如何在文本字段中用,替换.分隔符?用户可以输入5,6之类的内容,但是当他按下按钮时,我想将他输入的数据提交为5,65.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
}
}

2 个答案:

答案 0 :(得分:1)

单击按钮时,在代码下面写下替换字符串

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

答案 1 :(得分:0)

您应该为uitextfield添加Delegate方法

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))

}

现在您可以获取替换字符串以及当前的文本字段文本。!