使用 SwiftUI 时如何隐藏键盘? [英] How to hide keyboard when using SwiftUI?

查看:22
本文介绍了使用 SwiftUI 时如何隐藏键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在以下情况下使用 SwiftUI 隐藏 keyboard?

How to hide keyboard using SwiftUI for below cases?

案例 1

我有 TextField,当用户点击 return 按钮时,我需要隐藏 keyboard.

I have TextField and I need to hide the keyboard when the user clicks the return button.

案例 2

我有 TextField,当用户点击外面时,我需要隐藏 keyboard.

I have TextField and I need to hide the keyboard when the user taps outside.

我如何使用 SwiftUI 做到这一点?

How I can do this using SwiftUI?

注意:

我没有问过关于 UITextField 的问题.我想通过使用 SwifUI.TextField 来做到这一点.

I have not asked a question regarding UITextField. I want to do it by using SwifUI.TextField.

推荐答案

您可以通过向共享应用程序发送操作来强制第一响应者辞职:

You can force the first responder to resign by sending an action to the shared application:

extension UIApplication {
    func endEditing() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

现在您可以随时使用此方法关闭键盘:

Now you can use this method to close the keyboard whenever you desire:

struct ContentView : View {
    @State private var name: String = ""

    var body: some View {
        VStack {
            Text("Hello (name)")
            TextField("Name...", text: self.$name) {
                // Called when the user tap the return button
                // see `onCommit` on TextField initializer.
                UIApplication.shared.endEditing()
            }
        }
    }
}

如果你想通过点击关闭键盘,你可以创建一个带有点击动作的全屏白色视图,这将触发endEditing(_:):

If you want to close the keyboard with a tap out, you can create a full screen white view with a tap action, that will trigger the endEditing(_:):

struct Background<Content: View>: View {
    private var content: Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content()
    }

    var body: some View {
        Color.white
        .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        .overlay(content)
    }
}

struct ContentView : View {
    @State private var name: String = ""

    var body: some View {
        Background {
            VStack {
                Text("Hello (self.name)")
                TextField("Name...", text: self.$name) {
                    self.endEditing()
                }
            }
        }.onTapGesture {
            self.endEditing()
        }
    }

    private func endEditing() {
        UIApplication.shared.endEditing()
    }
}

这篇关于使用 SwiftUI 时如何隐藏键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆