Search code examples
iosswiftuitextfieldswift2uitextfielddelegate

UITextField to Input Money Amount


I am developing a Point Of Sales app.

So I would like to

  1. Let's say User input 100000 but I want it to automatically show up 100,000. and 1000000 become 1,000,000

  2. The second problem is that, I don't want user to be able to input . themselves.

  3. Third problem is that since this is money, we can't let user to enter 0 in the beginning.

Any ideas?

So far I have managed to restrict the input to decimal digits only

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

        let numberSet: NSCharacterSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet;
        return string.stringByTrimmingCharactersInSet(numberSet).length > 0 || string == "";
}

Thank you very much

P.S.: I do not need any decimal places, also we need to take into account when the user change the cursor position when hitting backspace


Solution

  • Xcode 9 • Swift 4

    import UIKit
    
    class IntegerField: UITextField {
        var lastValue = 0
        let maxValue = 1_000_000_000
        var amount: Int {
            if let newValue = Int(string.digits), newValue < maxValue {
                lastValue = newValue
            } else if !hasText {
                lastValue = 0
            }
            return lastValue
        }
        override func didMoveToSuperview() {
            textAlignment = .right
            keyboardType = .numberPad
            text = Formatter.decimal.string(for: amount)
            addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        }
        @objc func editingChanged(_ textField: UITextField) {
            text = Formatter.decimal.string(for: amount)
        }
    }
    

    extension NumberFormatter {
        convenience init(numberStyle: Style) {
            self.init()
            self.numberStyle = numberStyle
        }
    }
    struct Formatter {
        static let decimal = NumberFormatter(numberStyle: .decimal)
    }
    extension UITextField {
        var string: String { return text ?? "" }
    }
    
    extension String {
        private static var digitsPattern = UnicodeScalar("0")..."9"
        var digits: String {
            return unicodeScalars.filter { String.digitsPattern ~= $0 }.string
        }
    }
    
    extension Sequence where Iterator.Element == UnicodeScalar {
        var string: String { return String(String.UnicodeScalarView(self)) }
    }