主视图包含一个具有多个部分的表单,包括文本字段和导航链接。我使用了 @FocusState 变量,在进入主视图时自动弹出键盘,方便用户直接在 TextField 中输入内容。
但是,当我保持键盘打开并单击部分中的导航链接进入子视图时,我找不到在进入子视图时自动关闭键盘的方法。我见过几个苹果官方应用程序(例如“提醒”)实现了这一点。
不关闭键盘会导致它在返回主视图时再次自动弹出,并在控制台中触发“无法同时满足约束”错误。
我向 GPT 寻求帮助,但建议(例如使用 SimultaneousGesture 或将 isActive 添加到 NavigationLink(可能已弃用))并未奏效。 iOS开发中有人遇到过这个问题吗?
确保返回主视图时键盘不会再次弹出。
这是演示代码。
import SwiftUI
struct SwiftUIView: View {
@State private var text = ""
@FocusState private var isTextFieldFocused: Bool
var body: some View {
NavigationStack {
Form {
Section {
TextField("Enter something", text: $text)
.focused($isTextFieldFocused)
}
Section {
NavigationLink(destination: Text("11")) {
HStack {
Label {
Text("subview")
} icon : {
ZStack {
RoundedRectangle(cornerRadius: 6)
.foregroundColor(.orange)
.frame(width: 30, height: 30)
Image(systemName: "face.smiling")
.foregroundColor(.white)
}
}
}
}
}
}
}
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
在主视图和目标视图中使用
.onAppear
尝试这种方法。
示例代码:
struct SwiftUIView: View {
@State private var text = ""
@FocusState private var isTextFieldFocused: Bool
var body: some View {
NavigationStack {
Form {
Section {
TextField("Enter something", text: $text)
.focused($isTextFieldFocused)
}
Section {
NavigationLink(destination:
Text("11")
.onAppear {
isTextFieldFocused = false // <--- here
}
) {
HStack {
Label {
Text("subview")
} icon : {
ZStack {
RoundedRectangle(cornerRadius: 6)
.foregroundColor(.orange)
.frame(width: 30, height: 30)
Image(systemName: "face.smiling")
.foregroundColor(.white)
}
}
}
}
}
}
.onAppear {
isTextFieldFocused = true // <--- here
}
}
}
}