'SwiftUI Keyboard Toolbar Scope

Say we have the following view of two text fields:

struct ContentView: View {
    
    @State private var first = ""
    @State private var second = ""
    
    var body: some View {
        VStack {
            TextField("First", text: $first)
                .toolbar {
                    ToolbarItem(placement: .keyboard) {
                        Button("Test") { }
                    }
                }
            
            TextField("Second", text: $second)
        }
    }
}

The toolbar modifier is applied only to the "first" text field. My expectation is therefore that it only shows up on the keyboard, when the "first" text field is in focus. What happens in practice though, it that it also shows up when the "second" text field is in focus.

Is this intended behaviour? And if so, how can I have different keyboard toolbars for different text fields?



Solution 1:[1]

The only thing that I've found so far that solves this problem works, but doesn't feel right. It also generates some layout constraint warnings in the console.

If you wrap each TextField in a NavigationView each `TextField will have its own context and thus its own toolbar.

Something like this:

struct ContentView: View {
    
    @State private var first = ""
    @State private var second = ""
    
    var body: some View {
        VStack {
          NavigationView {
            TextField("First", text: $first)
                .toolbar {
                    ToolbarItem(placement: .keyboard) {
                        Button("Test") { }
                    }
                }
          }
          NavigationView {  
            TextField("Second", text: $second)
          }
        }
    }
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 sidekickr