UITextField输入金额

时间:2016-02-21 13:58:32

标签: ios swift uitextfield swift2 uitextfielddelegate

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

所以我想

  1. 我们说用户输入100000,但我希望它自动显示100,000。并1000000成为1,000,000

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

  3. 第三个问题是,由于这是钱,我们不能让用户在开头输入0。

  4. 有什么想法吗?

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

    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。:我不需要任何小数位,我们还需要在用户点击退格时更改光标位置时考虑

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

  

简单的事情我在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

OUTPUT