Swift 5: UITextField attributedText doesnt update when currency change

25 Views Asked by At

I have this CurrencyTextfield which is a CurrencyTextFieldRepresentable because I'm using it inside a SwiftUI view. I have an attributed string that I am updating in the init into setStyles() and in editingChanged(), the problem in when I change the currency with a ActionSheet in SwiftUI (this work fine), for example from ARS to USD in the textfield $0 is still seen when USD0 should be seen, however when I start to write for example 100 the text Its updated correctly to USD100. How can I make my textfield update when I change the type of currency? Not only when I'm editing. This is my code:

class TextFieldTest: UITextField {
@Binding private var amount: Int
@Binding var currency: Currency
init(amount: Binding<Int>, currency: Binding<Currency>) {
    self._amount = amount
    self._currency = currency
    super.init(frame: .zero)

    addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    addTarget(self, action: #selector(resetSelection), for: .allTouchEvents)
    delegate = self
    
    setStyles()
}
 @objc private func resetSelection() {
    selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
}
 @objc private func editingChanged() {
    attributedText = addAttributedString(amountString)
    amount = Int(amountString.onlyDigits) ?? 0
}
var decimal: Decimal {
    let numberString = textValue.onlyDigits
    let decimal = Decimal(string: numberString, locale: self.formatter.locale) ?? 0
    return decimal
}

var amountString: String {
    formatter.string(from: NSDecimalNumber(decimal: decimal)) ?? "0"
}

private func setStyles() {
    textAlignment = .center
    keyboardType = .decimalPad
    attributedText = addAttributedString(amountString)
    
}
   private func addAttributedString(_ string: String) -> NSMutableAttributedString {
    let mainString = currency.symbol + string
    let stringToColor = currency.symbol
    let range = (mainString as NSString).range(of: stringToColor)
    let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
    mutableAttributedString.addAttributes([
        .foregroundColor: .green,
        .font: .systemFont),
        .baselineOffset: 4
    ], range: range)
    
    return mutableAttributedString
 }
}
0

There are 0 best solutions below