用TextField中的小数点分隔符替换逗号
问题描述:
有人能告诉我如何用“。”替换“,”分隔符。在我的文本框?用户可以输入类似于“5,6”的东西,但是当他按下一个按钮时,我想将他输入的数据作为“5,6”输入到“5.6”,因为否则不会进行小数计算。用TextField中的小数点分隔符替换逗号
我有这个扩展字符串文件,但似乎工作仅限于1逗号文本的限制&逗号后面的2个十进制数,没有将“,”转换为“。”。
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 strReplace = txtField.text.replacingOccurrences(of: ",", with: ".", options: .literal, range: nil)// change "txtField" your textfield's object
print(\(strReplace))
答
您应该添加委派方法的UITextField
class ViewController: UIViewController, UITextFieldDelegate
然后添加self in viewdidload
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))
}
现在你能得到替换字符串以及什么目前文本框的文字!
谢谢!这工作! – AndreiVataselu