You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用.focused()修饰器实现点击其他视图时移除TextField焦点

代码修正方案

你的代码存在三处问题:

  • 变量名拼写错误:onTapGesture 闭包内引用的 state 不存在,你定义的对应变量是 focusState
  • 点击区域覆盖不全:仅为 Rectangle 绑定了点击事件,无法覆盖文本框外的所有视图区域
  • 冗余逻辑:不需要额外定义 .notTextField 枚举值,直接将 focusState 置为 nil 即可释放所有控件的焦点

修正后的完整代码如下:

enum Field {
  case textField
}

struct ContentView: View {
  @State private var textInput = ""
  @FocusState private var focusState: Field?

  var body: some View {
    VStack {
      TextField("Enter some text...", text: $textInput)
        .focused($focusState, equals: .textField)
    }
    // 撑满整个屏幕可用区域
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    // 让整个VStack的透明区域也能响应点击
    .contentShape(Rectangle())
    .onTapGesture {
      focusState = nil
    }
  }
}

改动说明:

  • 移除了冗余的 .notTextField 枚举值,简化逻辑
  • 外层 VStack 撑满整个屏幕,保证所有非文本框区域点击都能被捕获
  • .contentShape(Rectangle()) 修饰符解决了SwiftUI默认不响应透明区域点击的问题
  • 点击触发时直接将 focusState 置为nil,系统会自动移除当前 TextField 的焦点,收起软键盘

内容的提问来源于stack exchange,提问作者dooblr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:15:00