我如何删除TextField的焦点时,点击不同的视图使用.focused()?



我试图使用iOS15的.focused()修饰符,使用户能够在文本字段之外的任何地方点击以删除焦点。我要离开:https://www.youtube.com/watch?v=GqXVFXnLVH4中提供的示例。下面是我的非工作尝试:

enum Field {
case textField
case notTextField
}
struct ContentView: View {
@State var textInput = ""
@FocusState var focusState:Field?
var body: some View {
VStack {
TextField("Enter some text...", text: $textInput)
.focused($focusState, equals: .textField)
Rectangle()
.focused($focusState, equals: .notTextField)
.onTapGesture {
state = .notTextField
}
}
}
}

我发现解决方案不是关注另一个元素,而是将textfield的焦点切换为false:

@State var textInput = ""
@FocusState var textFieldIsFocused: Bool
var body: some View {
VStack {
TextField("Enter some text...", text: $textInput)
.focused($textFieldIsFocused)
Rectangle()
.onTapGesture {
textFieldIsFocused = false
}
}
}

最新更新