iosswiftuser-interfaceswiftuiuikit

How to add placeholder text to TextEditor in SwiftUI?


When using SwiftUI's new TextEditor, you can modify its content directly using a @State. However, I haven't see a way to add a placeholder text to it. Is it doable right now?

enter image description here

I added an example that Apple used in their own translator app. Which appears to be a multiple lines text editor view that supports a placeholder text.


Solution

  • It is not possible out of the box but you can achieve this effect with ZStack or the .overlay property.

    What you should do is check the property holding your state. If it is empty display your placeholder text. If it's not then display the inputted text instead.

    And here is a code example:

    ZStack(alignment: .leading) {
        if email.isEmpty {
            Text(Translation.email)
                .font(.custom("Helvetica", size: 24))
                .padding(.all)
        }
        
        TextEditor(text: $email)
            .font(.custom("Helvetica", size: 24))
            .padding(.all)
    }
    

    Note: I have purposely left the .font and .padding styling for you to see that it should match on both the TextEditor and the Text.

    EDIT: Having in mind the two problems mentioned in Legolas Wang's comment here is how the alignment and opacity issues could be handled:

    • In order to make the Text start at the left of the view simply wrap it in HStack and append Spacer immediately after it like this:
    HStack {
       Text("Some placeholder text")
       Spacer()
    }
    
    • In order to solve the opaque problem you could play with conditional opacity - the simplest way would be using the ternary operator like this:
    TextEditor(text: stringProperty)        
            .opacity(stringProperty.isEmpty ? 0.25 : 1)
    

    Of course this solution is just a silly workaround until support gets added for TextEditors.