I am developing a Point Of Sales app.
So I would like to
Let's say User input 100000
but I want it to automatically show up 100,000
. and 1000000
become 1,000,000
The second problem is that, I don't want user to be able to input .
themselves.
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
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)) }
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With