The SwiftUI TextEditor is like a versatile notepad for your app. It lets users input and edit text in a simple and interactive way. You can use it to create everything from basic notes to more complex forms in your SwiftUI-based application. It’s a handy tool for capturing user input and making your app more interactive and user-friendly.

SwiftUI TextEditor - Swiftui tutorial

Understanding the Basics

Getting Started with SwiftUI TextEditor

At its core, the TextEditor is SwiftUI’s answer to efficiently handling user input for text. Whether you’re building a note-taking app, a messaging platform, or anything in between, understanding the basics is fundamental.

struct MyTextView: View {
    @State private var text = "Start typing here..."

    var body: some View {
        TextEditor(text: $text)
            .frame(height: 200)
            .padding()
            .background(Color.gray.opacity(0.1))
            .cornerRadius(8)
    }
}

Here, the $text binding ensures real-time synchronization between the SwiftUI TextEditor and the underlying data, offering a seamless user experience.

Advanced Customization Techniques of SwiftUI TextEditor

Styling Your TextEditor

Take your UI to the next level by delving into advanced styling options. Customize fonts, colors, and alignments to align with your app’s aesthetic. Utilize modifiers such as .font(), .foregroundColor(), and .multilineTextAlignment() to tailor the TextEditor’s appearance.

TextEditor(text: $text)
    .font(.custom("Avenir", size: 16))
    .foregroundColor(.primary)
    .multilineTextAlignment(.justified)

Enabling Rich Text Editing

If your app demands more than plain text, SwiftUI’s TextEditor can handle attributed text. Leverage NSAttributedString to implement rich text features, allowing users to format text with bold, italics, and various colors.

TextEditor(text: $text)
    .allowsRichTextEditing(true)

Advanced Interaction and Validation

Implementing Interactive Features

Enhance user interaction by implementing features like clickable links within the TextEditor. Combine SwiftUI’s gesture recognizers with the TextEditor to create a seamless experience.

TextEditor(text: $text)
    .onTapGesture {
        // Implement your custom interaction logic here
    }

Validating User Input

Ensure data integrity by incorporating validation mechanisms. SwiftUI offers robust tools to validate and sanitize user input, preventing potential issues down the line.

TextEditor(text: $text)
    .onChange(of: text) { newValue in
        // Implement your validation logic here
    }

Optimizing Performance and Accessibility

Handling Large Text Data

Efficiently manage large sets of text data within the TextEditor by optimizing its performance. Implement techniques like lazy loading to enhance responsiveness and provide a smoother user experience.

ScrollView {
    TextEditor(text: $text)
        .frame(minHeight: 200)
}

Ensuring Accessibility for All Users

SwiftUI places a strong emphasis on accessibility. Make your TextEditor inclusive by incorporating accessibility features, ensuring a seamless experience for users with diverse needs.

TextEditor(text: $text)
.accessibilityLabel("User Input Area")
.accessibilityHint("Tap to start typing")

SwiftUI TextEditor Background Color

You should hide the default background to see your desired one:

TextEditor(text: .constant("Placeholder"))
    .scrollContentBackground(.hidden) // <- Hide it
    .background(.red) // To see this

TextEditor is backed by UITextView. So you need to get rid of the UITextView‘s backgroundColor first and then you can set any View to the background.

struct ContentView: View {
    init() {
        UITextView.appearance().backgroundColor = .clear
    }

    var body: some View {
        List {
            TextEditor(text: .constant("Placeholder"))
                .background(.red)
        }
    }
}
SwiftUI TextEditor Background Color

How do I create a multiline TextField in SwiftUI?

iOS 16+

TextField can be configured to expand vertically using the new axis parameter. Also, it takes the lineLimit modifier to limit the lines in the given range:

TextField("Title", text: $text,  axis: .vertical)
    .lineLimit(5...10)

The .lineLimit modifier now also supports more advanced behaviors, like reserving a minimum amount of space and expanding as more content is added, and then scrolling once the content exceeds the upper limit


iOS 14+

It is called TextEditor

struct ContentView: View {
    @State var text: String = "Multiline \ntext \nis called \nTextEditor"

    var body: some View {
        TextEditor(text: $text)
    }
}

🎁 Dynamic growing height:

If you want it to grow as you type, embed it in a ZStack with a Text like this:

How do I create a multiline TextField in SwiftUI?

iOS 13+

you can use the native UITextView right in the SwiftUI code with this struct:

struct TextView: UIViewRepresentable {
    
    typealias UIViewType = UITextView
    var configuration = { (view: UIViewType) in }
    
    func makeUIView(context: UIViewRepresentableContext<Self>) -> UIViewType {
        UIViewType()
    }
    
    func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<Self>) {
        configuration(uiView)
    }
}

Usage

struct ContentView: View {
    var body: some View {
        TextView() {
            $0.textColor = .red
            // Any other setup you like
        }
    }
}

How to bold text in SwiftUI TextField?

import SwiftUI

struct ContentView: View {
    @State var TextValue: String = "Hello"
    
    var body: some View {
        VStack {
            TextField("placeholder", text: $TextValue)
            .padding(.horizontal, 50)
                .font(.system(size: 30, weight: .heavy, design: .default))
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
How to bold text in SwiftUI TextField?

Texteditor SwiftUI Placeholder

Here’s a SwiftUI code snippet that implements a TextEditor with a placeholder:

Custom View of TextEditor Class:

import SwiftUI

struct TextEditorWithPlaceholder: View {
    
    @FocusState private var focusedField: Field?
    
    enum Field {
        case textEditor
        case placeholder
    }
    
    @Binding var text: String
    private let placeholderText: String
    
    init(_ placeholder: String, text: Binding<String>) {
        self._text = text
        self.placeholderText = placeholder
    }
    
    var body: some View {
        ZStack {
            
            // Show the placeholder if the text is empty
            if text.isEmpty {
                
                ZStack {
                    Rectangle()
                        .fill(Color(uiColor: .systemBackground))
                        .onTapGesture {
                            focusedField = .placeholder
                        }
                    
                    VStack {
                        HStack {
                            TextField(placeholderText, text: $text)
                                .focused($focusedField, equals: .placeholder)
                                .onAppear {
                                    focusedField = .placeholder
                                }
                                
                            Spacer()
                        }
                        .padding(.leading, 6)
                        .padding(.top, 8)
                        
                        Spacer()
                    }
                }

                // Show the text editor if the text is not empty
            } else {
                TextEditor(text: $text)
                    .focused($focusedField, equals: .textEditor)
                    .onAppear {
                        focusedField = .textEditor
                    }
            }
        }
    }
}

struct TextEditorWithPlaceholder_Previews: PreviewProvider {
    static var previews: some View {
        TextEditorWithPlaceholder("Write down...", text: .constant(""))
    }
}

Use Of this Class in main ContentView

import SwiftUI

struct ContentView: View {
    
    @FocusState private var isFocusedTextEditor: Bool
    @State private var text: String = ""
    
    var body: some View {
        ZStack {
            Rectangle()
                .fill(.black)
                .ignoresSafeArea()
            
            VStack {
                
                Text("iOS Examples")
                    .font(.title)
                    .foregroundColor(.white)
                    .bold()
                
                TextEditorWithPlaceholder("Write down...", text: $text)
                    .focused($isFocusedTextEditor)
            }
            .padding()
        }
        .onTapGesture {
            isFocusedTextEditor = false
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SwiftUI TextEditor Border

TextEditor(text: $text)
            .frame(minHeight: 200)
            .padding()
            .background(Color.gray.opacity(0.1))
            .cornerRadius(8)
            .border(Color.black, width: 1) // Add border here

Here Some Github SwiftUI TextEditor iOS Examples Link

#TextEditor

#TextMaster

Link, progressView, colorPicker, datePicker, textEditor, textField

SwiftUI TextEditor API with dynamic height by text line

ColorPicker-SwiftUI

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *