1

在 SwiftUI 上,您可以使用修饰符TextField为键盘的返回/提交按钮设置操作。.onSubmit()你如何达到同样的效果TextEditor?(.onSubmit()似乎不起作用。)

4

3 回答 3

3

您可以将 on change 用于绑定变量,TextEditor如下所示:

    TextEditor(text: $text)
        .onChange(of: text) { _ in
            if !text.filter({ $0.isNewline }).isEmpty {
                print("Found new line character")
            }
        }

意识到它TextEditor本身没有提交按钮。它旨在接受无限量的各种文本。

于 2021-12-11T21:32:23.213 回答
0

另一种了解用户何时创建新行的方法:

TextEditor(text: $text)
            .onChange(of: text) { string in
                for char in string
                {
                    if char() == "\n"
                    {
                        print("Found new line character")
                    }
                }
            }

Yrb 的回答和这个效果很好,但是一旦找到新行并且每次将新字符添加到 TextEditor 时,您都会执行相同的操作print("Found new line character")

如果您想知道每次用户按 Enter 键或创建新行时,这对您来说是一个更好的解决方案:

TextEditor(text: $text)
            .onChange(of: text) { string in
                if string.last == "\n"
                {
                    print("Found new line character")
                }
            }
于 2022-02-24T18:07:55.533 回答
-1

这是您的解决方案:

onCommit:当用户按下 Return 键时,TextField 会调用 onCommit 闭包。

于 2021-12-12T06:43:11.737 回答