Home > OS >  How do I show different buttons in the toolbar based on which field is focused in SwiftUI?
How do I show different buttons in the toolbar based on which field is focused in SwiftUI?

Time:09-01

I want to show different buttons based on what field is focused, but the focus state is allways one behind.

Here is the code:

struct ContentView: View {

    enum FocusField {
        case one
        case two
    }
    
    @FocusState var focused: FocusField?
    
    var body: some View {
        VStack {
            TextField("One", text: .constant(""))
                .focused($focused, equals: .one)
            TextField("Two", text: .constant(""))
                .focused($focused, equals: .two)
        }
        .toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                if focused == .one {
                    Text("One")
                } else if focused == .two {
                    Text("Two")
                } else {
                    Text("None")
                }
                Spacer()
                Button("Done") { focused = nil }
            }
        }
    }
}

CodePudding user response:

@FocusState can be a bit buggy at times. I could only speculate on the reason why your approach is not working. But consider this solution (tested on Xcode 13 and IOS 15):

struct ContentView33: View {
    // add confomance to String
    enum FocusField: String {
        case one = "One" // add rawValues
        case two = "Two"
    }
    
    @FocusState var focused: FocusField?
    
    var body: some View {
        VStack {
            TextField("One", text: .constant(""))
                .focused($focused, equals: .one)
            TextField("Two", text: .constant(""))
                .focused($focused, equals: .two)
        }
        .toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                //this will update the keyboard toolbar
                Text(focused?.rawValue ?? "None")
                Spacer()
                Button("Done") { focused = nil }
            }
        }
    }
}
  • Related