mica
mica

Reputation: 4308

SwiftUI on MacOS: Detect Focus Change and force Focus Change programaticly

I want to detect a Focus Change and force a Focus Change.
In this simple Example I want to detect, if a user klicks in one of the textfields.
On the other hand, I want so set the focus programaticly with a Button.

struct ContentView: View {

  @State private var textA = ""
  @State private var textB = ""

  @State private var focusableA = false
  @State private var focusableB = false

    var body: some View {
      VStack{
        HStack{
          TextField("Field A", text: $textA)
          .focusable(focusableA, onFocusChange: {f in print ("FocusChange A \(f)")})
          TextField("Field V", text: $textB)
          .focusable(focusableB, onFocusChange: {f in print ("FocusChange B \(f)")})
        }
        HStack{
          Button(action: {self.focusableA = true; self.focusableB = false }) 
          {Text("Set Focus to A")}
          Button(action: {self.focusableB = true; self.focusableA = false }) 
          {Text("Set Focus to B")
          }
        }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

The Code above does not work, how can this be done.

Upvotes: 1

Views: 1213

Answers (1)

Asperi
Asperi

Reputation: 258541

I want to detect, if a user clicks in one of the textfields.

Here is an example for this

TextField("Title", text: boundText, onEditingChanged: { editing in
            if editing {
                print(">> start editing, got focus")
            } else {
                print(">> end editing, lost focus")
            }
        })

I want so set the focus programaticly with a Button

SwiftUI itself does not give API for this for now. The .focusable gives capability to be focusable for views, which are not such by default (eg. Text), but not force-set focus.

Upvotes: 1

Related Questions