在UITextField退格期间,UITextLabel的更新顺序与其他条目不同。

时间:2018-09-21 06:49:15

标签: swift uitextfield swift4 currency

好的,所以我有一个UITextLabel,无论何时以及何时更改UITextField,它都将更新为任何内容。

所以我有以下方法。

func textField(_ textField: UITextField, shouldChangeCharactersInrange: NSRange, replacementString string: String) -> Bool {
    payment_amount_label.text = payment_amount_tf.text!
    return true
}

,并且我将文本字段设置为货币字段。这是代码。

class CurrencyField: UITextField {
    var string: String { return text ?? "" }
    var decimal: Decimal {
        return string.digits.decimal /
            Decimal(pow(10, Double(Formatter.currency.maximumFractionDigits)))
    }
    var decimalNumber: NSDecimalNumber { return decimal.number }
    var doubleValue: Double { return decimalNumber.doubleValue }
    var integerValue: Int { return decimalNumber.intValue   }
    let maximum: Decimal = 9_999.99
    private var lastValue: String?
    override func willMove(toSuperview newSuperview: UIView?) {
        // you can make it a fixed locale currency if needed
        // Formatter.currency.locale = Locale(identifier: "pt_BR") // or "en_US", "fr_FR", etc
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        keyboardType = .numberPad
        textAlignment = .right
        editingChanged()
    }
    override func deleteBackward() {
        text = string.digits.dropLast().string
        print("inside method delete" + text!)
        editingChanged()

        //backspace not working for editingchanged. not sure why.
    }
    @objc func editingChanged(_ textField: UITextField? = nil) {
        guard decimal <= maximum else {
            text = lastValue
            return
        }
        text = Formatter.currency.string(for: decimal)
        lastValue = text
        print("inside method editing" + text! + "last value is " + lastValue!)
        return
    }
}

extension NumberFormatter {
    convenience init(numberStyle: Style) {
        self.init()
        self.numberStyle = numberStyle
    }
}
extension Formatter {
    static let currency = NumberFormatter(numberStyle: .currency)
}
extension String {
    var digits: [UInt8] {
        return map(String.init).compactMap(UInt8.init)
    }
}
extension Collection where Iterator.Element == UInt8 {
    var string: String { return map(String.init).joined() }
    var decimal: Decimal { return Decimal(string: string) ?? 0 }
}
extension Decimal {
    var number: NSDecimalNumber { return NSDecimalNumber(decimal: self) }
}

当我在键盘上输入数字时,所有内容都会正确更新。但是,当我按退格键时,文本字段将保留旧值。我输入了一些打印语句,以查看发生了什么,以及在单击Backspace时,在CurrencyField代码内部删除之前更新了UITextLabel。按下数字后,将在CurrencyField代码之后更新UITextLabel。我不知道如何解决此问题,不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

UITextField添加与UITextView相同的值的自定义方法。

viewDidLoad中:

payment_amount_tf.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

textFieldDidChange声明为:

@objc func textFieldDidChange(_ sender: UITextField) {
    payment_amount_label.text = payment_amount_tf.text
}