SwiftUI 如何使用文本编辑器创建多行可编辑文本 TextEditor?

6 min read

要在 SwiftUI 中创建多行可编辑文本,可以使用 TextEditor 控件。下面是创建多行可编辑文本的基本步骤:

  1. 在视图中添加 TextEditor 控件。

  2. 创建绑定变量来存储用户输入的文本。

  3. 将绑定变量传递给 TextEditor 控件中的 text 参数。

  4. 为 TextEditor 控件添加边框和占位符文字。

下面是一个示例代码,用于创建一个多行可编辑文本框:

struct ContentView: View {
    @State private var text = ""
    
    var body: some View {
        VStack {
            Text("Enter some text:")
                .padding()
            
            TextEditor(text: $text)
                .border(Color.gray)
                .padding()
                .cornerRadius(5.0)
                .frame(height: 100)
                .foregroundColor(.black)
                .overlay(RoundedRectangle(cornerRadius: 5.0).stroke(Color.gray, lineWidth: 1))
                .padding(.horizontal, 10.0)
            
            Spacer()
        }
    }
}

在上面的代码中,我们使用 @State 属性包装器创建了一个名为 text 的绑定变量。然后,我们将该变量传递给 TextEditor 控件中的 text 参数。我们还添加了边框、占位符文字和一些其他样式来美化 TextEditor 控件。

使用上面的代码,我们可以在 SwiftUI 中创建一个多行可编辑文本框。用户可以在该文本框中输入任意数量的文本,并且该文本将存储在绑定变量中。