How to add placeholder text to TextEditor in SwiftUI?

Built-in TextEditor does not have a placeholder. This is very easy to do.

import SwiftUI

struct TextEditorView: View {
    
    @Binding var comment: String
    
    init(comment: Binding<String>) {
        self._comment = comment
        
        UITextView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            placeholder
                .padding(.leading, 10)
                .padding(.top, 7)
            textEditor
        }
        .padding()
        .background(Color(.sRGB, red: 0.85, green: 0.85, blue: 0.85, opacity: 1))
        .cornerRadius(10)
        .overlay(border)
    }
}

// MARK: - Views
private extension TextEditorView {
    
    var placeholder: some View {
        Text(comment.isEmpty ? "Please write your comment" : "")
            .foregroundColor(.gray)
            .font(.system(size: 14, weight: .regular, design: .default))
    }
    
    var textEditor: some View {
        TextEditor(text: $comment)
            .background(Color.clear)
            .foregroundColor(Color.black)
            .font(.system(size: 14, weight: .regular, design: .default))
            .frame(height: 80)
            .cornerRadius(10)
    }
    
    var border: some View {
        RoundedRectangle(cornerRadius: 10)
            .stroke(Color.gray, lineWidth: 1)
    }
}

File in my GitHub – link

One thought on “How to add placeholder text to TextEditor in SwiftUI?

Leave a Reply

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