如何在 SwiftUI 中添加编号/项目符号列表?

时间:2021-05-16 15:24:07

标签: swiftui swiftui-texteditor

如何在 TextEditor 中的 SwiftUI 中执行此操作?我想到了从键盘读取返回。 TextFieldonEditingChangedonCommit,但 TextEditor 没有。

在 Notes 应用程序中,它会自动检测编号列表,并具有用于添加项目符号列表的按钮。

我特别希望它在空行后添加数字/项目符号。 (如果可能)

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用 TextEditor 观察 onChange 文本的变化。然后。通过执行 [text] newText,您可以捕获旧值和新值。

  • text 是之前的文本
  • newText 是当前文本

您可以将这些比较为仅在用户添加字符时添加项目符号,而不是删除它们。

请注意,我的实现还不能处理粘贴大范围的文本。

struct ContentView: View {
    @State var text = "\u{2022} "

    var body: some View {
        TextEditor(text: $text)
            .frame(height: 400)
            .border(Color.black)
            .onChange(of: text) { [text] newText in
                if newText.suffix(1) == "\n" && newText > text {
                    self.text.append("\u{2022} ")
                }
            }
    }
}

When entering new lines, a bullet point is inserted at the start of the line

相关问题