How to add placeholder text to TextEditor in SwiftUI?

后端 未结 9 2328
逝去的感伤
逝去的感伤 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条回答
  •  耶瑟儿~
    2021-02-14 01:44

    There are some good answers here, but I wanted to bring up a special case. When a TextEditor is placed in a Form, there are a few issues, primarily with spacing.

    1. TextEditor does not horizontally align with other form elements (e.g. TextField)
    2. The placeholder text does not horizontally align with the TextEditor cursor.
    3. When there is whitespace or carriage return/newline are added, the placeholder re-positions to the vertical-middle (optional).
    4. Adding leading spaces causes the placeholder to disappear (optional).

    One way to fix these issues:

    Form {
        TextField("Text Field", text: $text)
    
        ZStack(alignment: .topLeading) {
            if comments.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                Text("Long Text Field").foregroundColor(Color(UIColor.placeholderText)).padding(.top, 8)
            }
            TextEditor(text: $comments).padding(.leading, -3)
        }
    }
    

提交回复
热议问题