将货币文本字段转换为快速5的两倍?

时间:2019-11-18 11:28:32

标签: swift uitextfield currency

我有使用此类的货币文本字段。工作正常(显示1000000-> 1,000,000)。如何从货币字符串转换回双值?请教我怎么做,非常感谢。

import UIKit

class CurrencyTextField: UITextField {
    var lastValue = 0
    let maxValue = 1_000_000_000_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 个答案:

答案 0 :(得分:1)

根据您在代码中显示的扩展名,这应该可以将货币字符串转换为Double值:

let doubleValue = Double(yourCurrencyString.digits)

用保存货币字符串的任何变量替换yourCurrencyString