按返回键“不”关闭软件键盘 - SwiftUI

2023-12-14

我想创建一个 TextField,可以在其中快速输入多个字符串项same字段,输入项目,然后点击return添加它。

我已经有了添加功能,但是我不想在每次按回车键将项目添加到列表时关闭键盘,因为这对于用户每次点击文本字段以返回该项目来说很麻烦键盘。

我正在寻找一个纯粹的 SwiftUI 解决方案如果可能的话。

我有什么:

import SwiftUI

struct StackOverflowSubmissions: View {

   @State var item: String = ""
   var body: some View {

      TextField("Enter item...", text: $item, onCommit: {

         // Add item to CoreData database

      })
         .textFieldStyle(RoundedBorderTextFieldStyle())
         .padding(5)
         .background(Color(.gray))
         .cornerRadius(10)
         .padding()
    }
}

struct StackOverflowSubmissions_Previews: PreviewProvider {
    static var previews: some View {
        StackOverflowSubmissions()
    }
}



这里是CustomTextField这不会最小化键盘而是下一个CustomTextView是专注的。这个过程一直持续到当前CustomTextField是最后一个CustomTextField.

struct CustomTextField: UIViewRepresentable {
    @Binding var text: String // String value of the TextView
    let placeholder: String // Placeholder Text
    let keyboardType: UIKeyboardType // Keypad layout type
    let tag: Int // Tag to recognise each specific TextView
    var commitHandler: (()->Void)? // Called when return key is pressed

    init(_ placeholder: String, text: Binding<String>, keyboardType: UIKeyboardType, tag: Int, onCommit: (()->Void)?) {
        self._text = text
        self.placeholder = placeholder
        self.tag = tag
        self.commitHandler = onCommit
        self.keyboardType = keyboardType
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UITextField {
        // Customise the TextField as you wish
        let textField = UITextField(frame: .zero)
        textField.keyboardType = self.keyboardType
        textField.delegate = context.coordinator
        textField.backgroundColor = UIColor(white: 0.0, alpha: 0.025)
        textField.layer.borderWidth = 0.5
        textField.layer.borderColor = UIColor.tertiaryLabel.cgColor
        textField.font = UIFont.systemFont(ofSize: 16.0, weight: .light)
        textField.layer.cornerRadius = 6
        textField.isUserInteractionEnabled = true
        textField.text = text
        textField.textColor = UIColor.lightGray
        textField.tag = tag
        textField.placeholder = placeholder

        // For left inner padding
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: 120))
        textField.leftView = paddingView
        textField.leftViewMode = UITextField.ViewMode.always

        return textField
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = self.text
        uiView.setContentHuggingPriority(.init(rawValue: 70), for: .vertical)
        uiView.setContentHuggingPriority(.defaultLow, for: .horizontal)
    }

    class Coordinator : NSObject, UITextFieldDelegate {

        var parent: CustomTextField

        init(_ uiTextView: CustomTextField) {
            self.parent = uiTextView
        }

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

            if let value = textField.text as NSString? {
                let proposedValue = value.replacingCharacters(in: range, with: string)
                parent.text = proposedValue as String
            }
            return true
        }

        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            if let nextTextField = textField.superview?.superview?.viewWithTag(textField.tag + 1) as? UITextField {
                nextTextField.becomeFirstResponder()
            } else {
                textField.resignFirstResponder()
            }
            return false
        }

        func textFieldDidEndEditing(_ textField: UITextField) {
            parent.commitHandler?()
        }
    }
}

Use CustomTextView in the ContentView像这样:

struct ContentView: View {
    @State var firstName: String = ""
    @State var lastName: String = ""
    @State var email: String = ""

    var body: some View {
        VStack {
            Text("First Name Value: \(firstName)")
            CustomTextField("First Name", text: self.$firstName, keyboardType: .default, tag: 1, onCommit: nil).padding().frame(height: 70)


            Text("Last Name Value: \(lastName)")
            CustomTextField("Last Name", text: self.$lastName, keyboardType: .default, tag: 2, onCommit: {
                    print("Last Name is: \(self.lastName)")
                }).padding().frame(minWidth: 0, maxWidth: .infinity, minHeight: 70, maxHeight: 70)


            Text("Email Value: \(email)")
            CustomTextField("Email", text: self.$email, keyboardType: .emailAddress, tag: 3, onCommit: {
                    print("Email is: \(self.email)")
                }).padding().frame(minWidth: 0, maxWidth: .infinity, minHeight: 70, maxHeight: 70)
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按返回键“不”关闭软件键盘 - SwiftUI 的相关文章

随机推荐

  • 如何使用 Zend 2 保存处理程序 DbTableGateway?

    The Zend Session 保存处理程序本教程提供了 DbTableGateway 的示例 其中使用未定义的 adapter 变量创建 TableGateway 我想使用处理程序来绑定会话管理器 来自教程的上一页 到我的数据库中的会话
  • 默认情况下使用多个字段进行多重搜索

    所以 有一个 jqGrid 带有声明 如下所示 grid jqGrid bunch of stuff searchGrid multipleSearch true 这很好 当我单击 搜索 按钮时 它会为我带来模式形式 我猜是第一列和 sop
  • 执行 C# 交互式 powershell 脚本

    假设我使用 C 执行 powershell 脚本 脚本执行的结果是请求凭据才能继续 Example Pipeline pipeline runspace CreatePipeline pipeline Commands AddScript
  • 如何在 WXP(和更新的 MSWindows)上使用 C# 终止所有[大]子进程

    问题 如何确定子进程中的所有进程流程树杀掉他们 我有一个用 C 编写的应用程序 它将 从服务器获取一组数据 生成第 3 方实用程序来处理数据 然后 将结果返回给服务器 这工作正常 但由于跑步消耗a lotCPU 和may需要长达一个小时 我
  • 具有 C++ 虚函数时的 GDB 不完整类型

    我刚刚注意到一些奇怪的事情 当我在类中添加 虚拟关键字 除构造函数之外的任何函数 时 我无法在 GDB 中显示对象的内容 GDB 说 不完整类型 这是代码 reco h ifndef RECO H define RECO H include
  • 使用 api 1.1 的 Twitter POST 问题

    我们刚刚更改为 Twitter api 1 1 现在发推文不起作用并返回错误 远程服务器返回错误 400 错误请求 对此进行的研究表明 这与身份验证有关 但我们正在发送刚刚从登录页面获得的 accessToken 和机密 在 api 1 0
  • Linux内核中使用的三个优先级有什么区别?

    我是 Linux 内核的新手 现在我正在研究 Linux 内核中的进程调度 Linux 中存在三种类型的优先级 静态优先级 动态优先级 实时优先级 现在我明白的是 静态优先级和动态优先级仅针对传统进程定义它们只能取 100 到 139 之间
  • 使用令牌保护 REST Web 服务 (Java)

    这个问题在某种程度上与下面链接的问题相关 但是 我需要更清楚地了解某些方面和一些附加信息 参考 REST Web 服务身份验证令牌实施 背景 我需要使用令牌实现 REST Web 服务的安全性 Web 服务旨在与 Java 客户端一起使用
  • 是否有 JavaFX 方法来测试坐标是否在闭合路径内?

    我试图找到一种 JavaFX 方法来检测坐标是否位于闭合路径内 我创建了以下示例 并研究了各种方法 但是没有任何效果如我所愿 只有在非矩形形状内时才返回 true Node contains 仅适用于形状的边缘 不适用于内部 Node in
  • 如果仅知道密钥和明文,则恢复 AES IV

    如果我以 AES CBC 模式解密密文 并且第一个块的解密明文与原始已知明文不匹配 则很明显用于解密的 IV 与加密期间使用的 IV 不匹配 用于加密或解密的 IV 均未知 如果我知道密文 我可以执行以下操作来查找加密期间使用的 IV 尝试
  • Python 中限制函数执行

    类似的问题和答案还有很多 但我仍然找不到可靠的答案 所以 我有一个函数 可能运行时间太长 函数是私有的 从某种意义上说我无法更改它的代码 我想将其执行时间限制为 60 秒 我尝试了以下方法 Python 信号 不适用于 Windows 和多
  • 在 Eclipse 中获取类中所有方法的概览

    我已经完成了相当多的 xCode 编程 发现类中方法的概述视角非常有用 它看起来像这样 MY GROUP 1 lt defined with pragma mark MY GROUP 1 M method11 M method12 M MY
  • 如何在按键时更改 pygame 中文本的颜色?

    当谈到 pygame 时 我是一个完全的业余爱好者 我需要制作一个程序 当文本沿不同方向传播时 该程序会改变文本的颜色 这意味着每次按键 上 下 左 右 颜色都会不同 到目前为止 我已经能够让文本向各个方向移动 但是我不明白如何改变颜色 任
  • 堆分配一个二维数组(不是指针数组)

    我正在编写 C 代码 我想堆分配 512 256 字节 为了我自己的方便 我希望能够使用语法 array a b 访问元素 没有算术来找到正确的索引 我在网上看到的每个教程都告诉我创建一个指针数组 该数组指向我想要在数组中包含的行的数组 这
  • 两个文本字段的总和 - javascript

    我在网上找到了 this 1 相当困难的 javascript 示例 并且我已经在我的网站上成功实现了它 但是 在本例中 我希望在一个新文本字段中获得两个小计的结果 传统的getElementbyId and total value tot
  • Mongoose:定义未找到文档的 404 状态不起作用

    我正在学习 MongoDB 和 mongoose 现在我在为我的路由处理程序定义 404 状态时遇到问题 这是代码 app get users id async req res gt const id req params id try c
  • Sql 层次结构 ID 按级别排序

    是否可以按层次结构 id 对层次结构中的 sql 数据进行排序 然后对每个级别按字母顺序排序 假设我们有一个员工表 其中根据员工 ID 列出了组织层次结构 鲍勃 5 有菲尔 17 和查理 28 向他汇报 乔西 6 有泰勒 15 和迈克 56
  • VBA 运行时错误中没有调试选项

    我使用的是 excel 2013 当出现运行时错误时 我没有得到任何调试选项 如何在运行时错误期间获得调试选项 编辑 我意识到我只在以下情况下遇到这个问题 通常我会得到调试选项 除了这种情况 特别痛苦的是它甚至不告诉我错误在哪一行 错误的屏
  • Promise : then 与 then + catch [重复]

    这个问题在这里已经有答案了 以下2个代码有什么区别吗 myPromise then function console log success catch function console log error myPromise then f
  • 按返回键“不”关闭软件键盘 - SwiftUI

    我想创建一个 TextField 可以在其中快速输入多个字符串项same字段 输入项目 然后点击return添加它 我已经有了添加功能 但是我不想在每次按回车键将项目添加到列表时关闭键盘 因为这对于用户每次点击文本字段以返回该项目来说很麻烦