How to add placeholder text to TextEditor in SwiftUI?

后端 未结 9 2331
逝去的感伤
逝去的感伤 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:41

    I built a custom view that can be used like this (until TextEditor officially supports it - maybe next year)

    TextArea("This is my placeholder", text: $text)
    

    Full solution below:

    struct TextArea: View {
        private let placeholder: String
        @Binding var text: String
        
        init(_ placeholder: String, text: Binding) {
            self.placeholder = placeholder
            self._text = text
        }
        
        var body: some View {
            TextEditor(text: $text)
                .background(
                    HStack(alignment: .top) {
                        text.isBlank ? Text(placeholder) : Text("")
                        Spacer()
                    }
                    .foregroundColor(Color.primary.opacity(0.25))
                    .padding(EdgeInsets(top: 0, leading: 4, bottom: 7, trailing: 0))
                )
        }
    }
    
    extension String {
        var isBlank: Bool {
            return allSatisfy({ $0.isWhitespace })
        }
    }
    

    I'm using the default padding of the TextEditor here, but feel free to adjust to your preference.

提交回复
热议问题