0

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
 }
}
akitainu22
  • 95
  • 1
  • 8
  • Binding Is for SwiftUI views not UIKit classes there is no reason why this would work. UIKit isn’t capable of observing or updating most SwiftUI wrappers. Don’t include Binding inside any class. – lorem ipsum Jun 15 '23 at 18:13

0 Answers0