Home > Software engineering >  Placeholder text not showing on TextEditor
Placeholder text not showing on TextEditor

Time:11-08

Trying to create a interface that users can write a string of text that wraps around on the screen.

I created a SwiftUI page called 'TextArea' that I can call on another page when I need it. Since TextEditor cant put placeholder text. I needed to create one, this is my code here that I got from other users.

import SwiftUI
import UIKit

struct TextArea: View {
    @Binding var text: String
    let placeholder: String
    
    init(_ placeholder: String, text: Binding<String>) {
        self.placeholder = placeholder
        self._text = text
        UITextView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            
            if text.isEmpty {
                Text(placeholder)
                    .foregroundColor(Color(.placeholderText))
                    .padding(.horizontal, 8)
                    .padding(.vertical, 12)
            }
            
            TextEditor(text: $text)
                .padding(4)
        }
        .font(.body)
    }
}

Then on another SwiftUI page I call it with this block of code.

    TextArea("What's Happening", text: $caption)

At the top of that page I establish it

    @State private var caption = ""

The code compiles with no errors and builds no problem in the emulator. When I run the app, there is no placeholder text. The TextEditor works fine and as expected. The only thing that is missing is the placeholder text.

Thanks in advance!

CodePudding user response:

ZStack place view from bottom to top.

so that swap your placeholder view and TextEditor.

struct TextArea: View {
    @Binding var text: String
    let placeholder: String
    
    init(_ placeholder: String, text: Binding<String>) {
        self.placeholder = placeholder
        self._text = text
        UITextView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            TextEditor(text: $text) // <= Here
                .padding(4)
            
            if text.isEmpty {
                Text(placeholder)
                    .foregroundColor(Color(.placeholderText))
                    .padding(.horizontal, 8)
                    .padding(.vertical, 12)
            }
        }
        .font(.body)
    }
}

  • Related