'SwiftUI how to update FocusState.Binding?

I have a Text Field wrapper like this:

public struct SUIDoubleField: View {
  
  @Binding
  private var value: Double

  private let placeholder: String
  private let formatter: NumberFormatter
  
  private var focused: FocusState<Bool>.Binding
  
  public init(value: Double, placeholder: String, formatter: NumberFormatter, focused: FocusState<Bool>.Binding, onChange: @escaping (Double) -> Void) {
    _value = Binding(
      get: { value },
      set: { onChange($0) })
    self.placeholder = placeholder
    self.formatter = formatter
    self.focused = focused
  }
  
  public var body: some View {
    TextField(placeholder, value: $value, formatter: formatter)
      .focused(focused)
      .textFieldStyle(.roundedBorder)
      .keyboardType(.decimalPad)
      .toolbar {
        ToolbarItemGroup(placement: .keyboard) {
          Button(LOC(.dismissKeyboardButton)) {
            focused = false // Error
          }
        }
      }
  }
}

Here I am not able to update the focus value. I got these 2 errors:

Cannot assign to property: 'self' is immutable
Cannot assign value of type 'Bool' to type 'FocusState<Bool>.Binding'

I have tried passing onDone callback, and update the focused state from outside this component. This works well, but I think it's more convenient to pass in the binding. How can I do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source