UITextField输入金额 [英] UITextField to Input Money Amount
问题描述
我正在开发销售点应用程序。
I am developing a Point Of Sales app.
所以我想
-
假设用户输入
100000
但我希望它自动显示100,000
。和1000000
成为1,000,000
Let's say User input
100000
but I want it to automatically show up100,000
. and1000000
become1,000,000
第二个问题是,我不希望用户能够输入。
本身。
The second problem is that, I don't want user to be able to input .
themselves.
第三个问题是,由于这是钱,我们不能让用户在开头输入0。
Third problem is that since this is money, we can't let user to enter 0 in the beginning.
任何想法?
到目前为止,我已经管理过将输入限制为仅十进制数字
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 == "";
}
非常感谢
PS:我不需要任何小数位,我们也需要在用户点击退格时更改光标位置时考虑
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)) }
}
这篇关于UITextField输入金额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!