How do you dynamically format a number to have commas in a UITextField entry?

前端 未结 9 2038
傲寒
傲寒 2020-12-08 17:42

I want to have commas dynamically added to my numeric UITextField entry while the user is typing.

For example: 123,456 and 12,345,678

9条回答
  •  轮回少年
    2020-12-08 18:19

    I have another one. Fix some bugs with local configuration and zero after decimal point

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let point = Locale.current.decimalSeparator!
        let decSep = Locale.current.groupingSeparator!
        
        
        let text = textField.text!
        let textRange = Range(range, in: text)!
        
        var fractionLength = 0
        var isRangeUpperPoint = false
        
        if let startPoint = text.lastIndex(of: point.first!) {
            let end = text.endIndex
            let str = String(text[startPoint..= startPoint
        }
        
        if  fractionLength == 3 && string != "" && isRangeUpperPoint {
            return false
        }
        
        let r = (textField.text! as NSString).range(of: point).location < range.location
        if (string == "0" || string == "") && r {
            return true
        }
        
        // First check whether the replacement string's numeric...
        let cs = NSCharacterSet(charactersIn: "0123456789\(point)").inverted
        let filtered = string.components(separatedBy: cs)
        let component = filtered.joined(separator: "")
        let isNumeric = string == component
        
        
        if isNumeric {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            formatter.maximumFractionDigits = 2
            // Combine the new text with the old; then remove any
            // commas from the textField before formatting
            
            
            let newString = text.replacingCharacters(in: textRange,  with: string)
            
            
            let numberWithOutCommas = newString.replacingOccurrences(of: decSep, with: "")
            let number = formatter.number(from: numberWithOutCommas)
            if number != nil {
                var formattedString = formatter.string(from: number!)
                // If the last entry was a decimal or a zero after a decimal,
                // re-add it here because the formatter will naturally remove
                // it.
                if string == point && range.location == textField.text?.count {
                    formattedString = formattedString?.appending(point)
                }
                textField.text = formattedString
            } else {
                textField.text = nil
            }
        }
        
        
        
       return false
        
    }
    

提交回复
热议问题