Home > Enterprise >  SwiftUI FocusState not working in popover
SwiftUI FocusState not working in popover

Time:11-11

I would like to activate textfield with keyboard when popover appears, same as a user tap, but while working in a regular view, the following code does not work when presented in popover.

Any solutions? Thank you.

struct ContentView: View {
    
    @State var str = ""
    @State var show = false
    
    @FocusState private var focused: Bool

    var body: some View {
        VStack {
            Text("Popover")
                .onTapGesture {
                    show.toggle()
                }
                .popover(isPresented: $show) {
                    TextField("Popover Textfield", text: $str)
                        .focused($focused)
                        .onAppear {
                            focused = true
                        }
                }
                .frame(width: 100, height: 100)
        }
    }
}

CodePudding user response:

@FocusState is bounded to the root view, just split it like so:

import SwiftUI

                struct focusText: View {
                    @State var str = ""
                    @State var show = false
                    
                    var body: some View {
                        VStack {
                            Text("Popover")
                                .onTapGesture {
                                    show.toggle()
                                }
                                .popover(isPresented: $show) {
                                    popView(str: $str)
                                }
                        }
                        .frame(width: 100, height: 100)
                    }
                }


                struct popView: View {
                    @Binding var str: String
                    @FocusState private var focused: Bool
                    
                    var body: some View {
                        VStack {
                            TextField("Popover Textfield", text: $str)
                                .focused($focused)
                        }
                        .onAppear {
                            focused = true
                        }
                        
                    }
                    
                }

Remember that by default the simulator does not show the keyboard.

enter image description here

  • Related