How to add placeholder text to TextEditor in SwiftUI?

后端 未结 9 2329
逝去的感伤
逝去的感伤 2021-02-14 01:35

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?<

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 01:46

    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.

提交回复
热议问题