我有以下简单的代码,它将
Button
放在 View
上,点击时,在 TextField
上呈现 .sheet
:
struct TestView: View
{
@State private var sheetIsPresented: Bool = false
@State private var userInput: String = ""
@FocusState private var textFieldIsFocused: Bool
var body: some View
{
Button("Hello")
{
self.sheetIsPresented = true
}
.buttonStyle(.borderedProminent)
.sheet(isPresented: self.$sheetIsPresented)
{
HStack
{
Text("Name:")
TextField("Enter name", text: self.$userInput).focused(self.$textFieldIsFocused)
.onChange(of: self.textFieldIsFocused)
{
print("textFieldIsFocused")
}
}
}
}
}
当
TextField
被激活并且键盘出现时, .onChange
不会出现,并且“textFieldIsFocused”不会打印到控制台。然而,当我将 TextField
的代码从 .sheet
移到 View
本身时,它工作得很好。当 FocusState
位于 TextField
上时,如何才能使此 .sheet
属性起作用?
当您将工作表内容分解到单独的视图中时,它会起作用:
struct TestViewSheet: View {
@Binding var userInput: String
@FocusState private var textFieldIsFocused: Bool
var body: some View {
HStack {
Text("Name:")
TextField("Enter name", text: $userInput)
.focused($textFieldIsFocused)
.onChange(of: textFieldIsFocused) {
print("textFieldIsFocused")
}
}
}
}
struct TestView: View {
@State private var sheetIsPresented: Bool = false
@State private var userInput: String = ""
var body: some View {
Button("Hello") {
sheetIsPresented = true
}
.buttonStyle(.borderedProminent)
.sheet(isPresented: $sheetIsPresented) {
TestViewSheet(userInput: $userInput)
}
}
}