Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/96.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在输入数字块的最后添加3个零_Ios_Swift_Uitextfield - Fatal编程技术网

Ios UITextField在输入数字块的最后添加3个零

Ios UITextField在输入数字块的最后添加3个零,ios,swift,uitextfield,Ios,Swift,Uitextfield,我创建了一个UITextField,允许用户输入唯一的数字,然后在数字字符串的最后自动添加3个零(使用点分隔符,但现在它只显示为逗号而不是点)。例如,如果我输入3,文本字段中的字符串将为3.000,并限制为12个字符的输入 但现在我有一个问题,我一次只能输入一个数字,当我输入另一个数字时,它会替换我输入的旧数字。例如,我在文本字段中键入3,它变为3.000,然后键入2它变为2.000,而不是32.000。下面是我处理键入操作的代码: public func textField(_ textFie

我创建了一个
UITextField
,允许用户输入唯一的数字,然后在数字字符串的最后自动添加3个零(使用点分隔符,但现在它只显示为逗号而不是点)。例如,如果我输入
3
,文本字段中的字符串将为
3.000
,并限制为12个字符的输入

但现在我有一个问题,我一次只能输入一个数字,当我输入另一个数字时,它会替换我输入的旧数字。例如,我在文本字段中键入
3
,它变为
3.000
,然后键入
2
它变为
2.000
,而不是
32.000
。下面是我处理键入操作的代码:

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    self.textField?.text = textField.text

    let strTextOld = textField.text ?? ""
    let numStringOld = strTextOld.replacingOccurrences(of: ".", with: "", options: String.CompareOptions.literal, range: nil)
    var newValue: String = ""

    if let digit = Int(string) {
        let doubleItem = Int(numStringOld) ?? 0
        let itemNew = ((doubleItem/1000) * 10) + (Int(string) ?? 0)

        newValue = "\(itemNew * 1000)"
    }

    if string == "" {
        let doubleItem = Int(numStringOld) ?? 0
        let itemNew = Int((doubleItem / 1000) / 10)

        newValue = "\(itemNew * 1000)"
    }

    guard let text: String = textField.text else {return true}

    if newValue.length <= 12 {
        return self.formatPrice(textFormat: newValue, labelFormat: textField)
    }

    return true
}

//format price for textfield
func formatPrice(textFormat: String, labelFormat: UITextField) -> Bool {

    let formatStyle = NumberFormatter()
    formatStyle.numberStyle = .decimal

    let number = Double(textFormat.replaceMatches(regexp: "[^0-9]", with: ""))

    if let number:NSNumber = NSNumber(value: number ?? 0) {
        var strValue:String = formatStyle.string(from: number) ?? ""
        formatStyle.decimalSeparator = "."
        _ = strValue.replacingOccurrences(of: ",", with: ".")

        if number == 0 {
            strValue = ""
        }

        if labelFormat === self.textField {

            self.textField?.text = "\(strValue)"

        }

        return true
    }

    return true
}
public func textField(textField:UITextField,shouldChangeCharacters范围:NSRange,replacementString:string)->Bool{
self.textField?.text=textField.text
让strTextOld=textField.text??“”
让numStringOld=strTextOld.replacingOccurrences(of:“.”,with:”,选项:String.CompareOptions.literal,范围:nil)
var newValue:String=“”
如果let digit=Int(字符串){
设doubleItem=Int(numStringOld)??0
设itemNew=((doubleItem/1000)*10)+(Int(string)??0)
newValue=“\(itemNew*1000)”
}
如果字符串==“”{
设doubleItem=Int(numStringOld)??0
设itemNew=Int((doubleItem/1000)/10)
newValue=“\(itemNew*1000)”
}
guard let text:String=textField.text else{return true}
如果newValue.length Bool{
让formatStyle=NumberFormatter()
formatStyle.numberStyle=.decimal
让number=Double(textFormat.replaceMatches(regexp:“[^0-9]”,带:“”)
如果let number:NSNumber=NSNumber(值:number±0){
var strValue:String=formatStyle.String(from:number)?“”
formatStyle.decimalSeparator=“”
_=strValue.replacingOccurrences(of:,,with:“.”)
如果数字==0{
strValue=“”
}
如果labelFormat==self.textField{
self.textField?.text=“\(标准值)”
}
返回真值
}
返回真值
}

我添加了文档,让您了解每个步骤:

     let formatter: NumberFormatter = {
       let formatter = NumberFormatter()
       formatter.locale = Locale.current
       formatter.currencySymbol = ""
       formatter.numberStyle = .currency
       formatter.maximumFractionDigits = 0
       return formatter
     }()

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let suffix = ".000"
        // using NSString will allow us to replase replacing characters in range and get the newString
        guard let nsString = textField.text?.replacingOccurrences(of: suffix, with: "") as NSString? else { return false }
        // The newString that will be achieved after this function returns
        var newString = nsString.replacingCharacters(in: NSRange(location: (range.location - suffix.count) < 0 ? 0 : range.location - suffix.count, length: range.length > nsString.length ? nsString.length : range.length), with: string)

        // Going to delete a character.
        if string.isEmpty {
            // The reason we have an extra "0" is because after we return "true" the last digit will be deleted.
            textField.text = !newString.isEmpty ? "\(addCommas(to: newString.replacingOccurrences(of: ",", with: "")))\(suffix)0" : " "
            return true
        } else if newString.count <= 15 { // Going to add a character.
            newString = "\(addCommas(to: newString.replacingOccurrences(of: ",", with: "")))\(suffix)"
            textField.text = newString
        }
        return false
     }

    func addCommas(to string: String) -> String {
       guard let newNumber = Float(string) else { return string }
       return formatter.string(from: NSNumber(value: newNumber)) ?? string
    }
let格式化程序:NumberFormatter={
let formatter=NumberFormatter()
formatter.locale=locale.current
formatter.currencySymbol=“”
formatter.numberStyle=.currency
formatter.maximumFractionDigits=0
返回格式化程序
}()
func textField(textField:UITextField,shouldChangeCharacters范围:NSRange,replacementString:string)->Bool{
让后缀“.000”
//使用NSString将允许我们重放替换范围内的字符并获取新闻字符串
guard let nsString=textField.text?.replacingOccurrences(of:后缀,带:“”)作为nsString?否则{return false}
//此函数返回后将实现的新闻字符串
var newString=nsString.replacingCharacters(in:NSRange(location:(range.location-suffix.count)<0?0:range.location-suffix.count,length:range.length>nsString.length?nsString.length:range.length),with:string)
//将删除一个字符。
如果string.isEmpty{
//我们有一个额外的“0”是因为在返回“true”后,最后一个数字将被删除。
textField.text=!newString.isEmpty?\(添加逗号(到:newString.replacingOccurrences(of:,“,with:”))\(后缀)0:“”
返回真值
}else if newString.count字符串{
guard let newNumber=Float(string)else{return string}
返回格式化程序.string(from:NSNumber(value:newNumber))??string
}

我添加了文档,让您了解每个步骤:

     let formatter: NumberFormatter = {
       let formatter = NumberFormatter()
       formatter.locale = Locale.current
       formatter.currencySymbol = ""
       formatter.numberStyle = .currency
       formatter.maximumFractionDigits = 0
       return formatter
     }()

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let suffix = ".000"
        // using NSString will allow us to replase replacing characters in range and get the newString
        guard let nsString = textField.text?.replacingOccurrences(of: suffix, with: "") as NSString? else { return false }
        // The newString that will be achieved after this function returns
        var newString = nsString.replacingCharacters(in: NSRange(location: (range.location - suffix.count) < 0 ? 0 : range.location - suffix.count, length: range.length > nsString.length ? nsString.length : range.length), with: string)

        // Going to delete a character.
        if string.isEmpty {
            // The reason we have an extra "0" is because after we return "true" the last digit will be deleted.
            textField.text = !newString.isEmpty ? "\(addCommas(to: newString.replacingOccurrences(of: ",", with: "")))\(suffix)0" : " "
            return true
        } else if newString.count <= 15 { // Going to add a character.
            newString = "\(addCommas(to: newString.replacingOccurrences(of: ",", with: "")))\(suffix)"
            textField.text = newString
        }
        return false
     }

    func addCommas(to string: String) -> String {
       guard let newNumber = Float(string) else { return string }
       return formatter.string(from: NSNumber(value: newNumber)) ?? string
    }
let格式化程序:NumberFormatter={
let formatter=NumberFormatter()
formatter.locale=locale.current
formatter.currencySymbol=“”
formatter.numberStyle=.currency
formatter.maximumFractionDigits=0
返回格式化程序
}()
func textField(textField:UITextField,shouldChangeCharacters范围:NSRange,replacementString:string)->Bool{
让后缀“.000”
//使用NSString将允许我们重放替换范围内的字符并获取新闻字符串
guard let nsString=textField.text?.replacingOccurrences(of:后缀,带:“”)作为nsString?否则{return false}
//此函数返回后将实现的新闻字符串
var newString=nsString.replacingCharacters(in:NSRange(location:(range.location-suffix.count)<0?0:range.location-suffix.count,length:range.length>nsString.length?nsString.length:range.length),with:string)
//将删除一个字符。
如果string.isEmpty{
//我们有一个额外的“0”是因为在返回“true”后,最后一个数字将被删除。
textField.text=!newString.isEmpty?\(添加逗号(到:newString.replacingOccurrences(of:,“,with:”))\(后缀)0:“”
返回真值
}else if newString.count字符串{
guard let newNumber=Float(string)else{return string}
返回格式化程序.string(from:NSNumber(value:newNumber))??string
}

这只是在字符串的最后添加
.000
,最大字符数为12,但不包括添加3个零。因此我可以输入15个字符(12是限制字符,3个零)像这样:
321654987777.000
并且它不是
.000
之前数字的十进制分隔符格式。你能更新你的答案吗?谢谢你的答案。这就是我想要的。但是我注意到这一行:
var newString=nsString?.replacingCharacters(在:NSRange(位置:(range.location-suffix.count)<0?0:range.location-4,长度:range.length),带:string)??“
选择全部并按delete键时崩溃