Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Created June 13, 2021 13:41
Show Gist options
  • Save StewartLynch/f214aba14085df86f2ef652aa77463bc to your computer and use it in GitHub Desktop.
Save StewartLynch/f214aba14085df86f2ef652aa77463bc to your computer and use it in GitHub Desktop.
Example of Xcode 13 FocusState not working on Modal Sheets
import SwiftUI
enum Field {
case text1
}
struct ContentView: View {
// This works fine
@State private var showModal = false
@State private var text1:String = ""
@FocusState private var focusedField: Field?
var body: some View {
VStack {
TextField("enter text", text: $text1)
.focused($focusedField, equals: .text1)
.textFieldStyle(.roundedBorder)
.padding()
.task {
focusedField = .text1
}
Button {
showModal = true
} label: {
Text("Show modal")
}
}
.sheet(isPresented: $showModal) {
ModalSheet()
}
}
}
struct ModalSheet: View {
// This does not work at all.
@State private var text1:String = ""
@FocusState private var focusedField: Field?
var body: some View {
VStack {
TextField("enter text", text: $text1)
.focused($focusedField, equals: .text1)
.textFieldStyle(.roundedBorder)
.padding()
.task {
focusedField = .text1
}
// This does not work either
Button("Set Focus") {
focusedField = nil
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment