UITextField输入金额 [英] UITextField to Input Money Amount

查看:269
本文介绍了UITextField输入金额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing a Point Of Sales app.

所以我想


  1. 假设用户输入 100000 但我希望它自动显示 100,000 。和 1000000 成为 1,000,000

  1. 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.

第三个问题是,由于这是钱,我们不能让用户在开头输入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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆