Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI how to update FocusState.Binding?

Tags:

swiftui

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?


1 Answers

A value should be assigned to wrapped value not to binding itself, like

  Button(LOC(.dismissKeyboardButton)) {
    focused.wrappedValue = false // << here !!
  }
like image 159
Asperi Avatar answered Aug 12 '26 16:08

Asperi