首页 > 解决方案 > 使用 .focused() 点击不同视图时如何移除 TextField 焦点?

问题描述

我正在尝试使用 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
        }
    }
  }
}

标签: swiftswiftuiios15

解决方案


我发现解决方案不是聚焦另一个元素,而是将文本字段的焦点切换为 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
            }
    }
}

推荐阅读