JayVDiyk
JayVDiyk

Reputation: 4487

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

Upvotes: 7

Views: 6998

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236360

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

Upvotes: 6

O-mkar
O-mkar

Reputation: 5658

Simple thing i came up with fully tested on Swift 2.0

you can use the any of the textField delegate see which one suites you

         let price = Int(textField.text!)

        let _curFormatter : NSNumberFormatter = NSNumberFormatter()

        _curFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle

        _curFormatter.currencyCode = "INR"

        _curFormatter.maximumFractionDigits = 0

        let total = _curFormatter.stringFromNumber(price!)

        textField.text = total

OUTPUT

Upvotes: 2

Related Questions