UITextField 输入金额

UITextField to Input Money Amount

我正在开发一个销售点应用程序。

所以我想

  1. 假设用户输入 100000 但我希望它自动显示 100,0001000000 变成 1,000,000

  2. 第二个问题是,我不希望用户能够自己输入 .

  3. 第三个问题,既然是钱,我们不能让用户一开始就输入0。

有什么想法吗?

到目前为止,我已经设法将输入限制为十进制数字

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

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

非常感谢

P.S.: 我不需要任何小数位,我们还需要考虑用户在按下退格键时更改光标位置

Simple thing i came up with fully tested on Swift 2.0

您可以使用任何一个 textField 委托来查看哪一个套件适合您

         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

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 ~= [=11=] }.string
    }
}

extension Sequence where Iterator.Element == UnicodeScalar {
    var string: String { return String(String.UnicodeScalarView(self)) }
}