SwiftUI点击空白处收起键盘

import SwiftUI

struct ContentView: View {
    @State private var text: String = ""
    
    var body: some View {
        VStack {
            TextField("请输入文本", text: $text)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
                .frame(maxWidth: .infinity)
                .background(Color.gray.opacity(0.2))
                .padding()

            Spacer()
        }
        .contentShape(Rectangle()) // 使整个 VStack 可点击
        .onTapGesture {
            // 点击空白处收起键盘
            hideKeyboard()
        }
        .padding()
    }
}

// 扩展UIViewController来隐藏键盘
extension View {
    func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

代码解析

  • TextField:用于输入文本。
  • onTapGesture:当点击空白处时触发,调用 hideKeyboard() 方法。
  • hideKeyboard():通过发送 resignFirstResponder 的动作来收起键盘。

注意事项

  • 确保 contentShape(Rectangle()) 被添加到 VStack,这样整个区域都可以响应点击事件。
  • 你可以根据需要自定义视图的布局和样式。

猜你喜欢

转载自blog.csdn.net/qq_24459277/article/details/142547243