SwiftUI_visionOS_Note

TextEditor()

Jan 15, 2024
1 min read|
  • It allows for multi-line text input
  • We can allow users to add multiple lines of text
    • fits for features like user profile bios

1. Add a Text Editor in VStack

NavigationStack{
            VStack{
                TextEditor(text: .constant("Placeholder"))
            }        
            
            .navigationTitle(Text("Title"))
        }
swift

2. Bind the empty string to TextEditor

@State var textEditorText: String = ""
        
        NavigationStack{
            VStack{
                TextEditor(text: $textEditorText)
            }
            
            .navigationTitle(Text("Title"))
        }
swift

3. Add a button, and change the default string value

@State var textEditorText: String = "This is the starting text."
        
        NavigationStack{
            VStack{
                TextEditor(text: $textEditorText)
                Button(action: {}, label: {
                    Text("Button".uppercased())
                        .font(.headline)
                        .foregroundStyle(.white)
                        .padding()
                        .frame(maxWidth:. infinity)
                })
            }
            .padding()
            .navigationTitle(Text("If you read this, press like button"))
        }
swift

4. Add a height to textEditor

  • by default, textEditor has maxHeight of infinity
TextEditor(...)
	.frame(height: 250)
swift

  • Add a spacer after the button
VStack{
	TextEditor9...)
	Button(...)
	Spacer()
}
swift

5. Save text under the button

  1. Create empty string of var
@State var savedText: String = ""
swift

  1. Add a empty string text under the button
Text(savedText)
swift

  1. Bind the savedText to textEditorText under the button action
action: {

	savedText = textEditorText
}
swift

6. Customize TextEditor

TextEditor()
.frame(height: 250)
.foregroundStyle(.red)
.clipShape()
swift

Subscribe to our newsletter

Get the latest news and updates from our team