Skip to content

Instantly share code, notes, and snippets.

@aaronlab
Last active December 27, 2023 05:25
Show Gist options
  • Save aaronlab/1cff99fc70c2e39c11087e78429d21e8 to your computer and use it in GitHub Desktop.
Save aaronlab/1cff99fc70c2e39c11087e78429d21e8 to your computer and use it in GitHub Desktop.
SwiftUI TextEditor Placeholder
struct TextEditorPlaceHolder: View {
@State private var text: String = ""
private let screenWidth = UIScreen.main.bounds.width
var body: some View {
VStack {
ZStack(alignment: .leading) {
if self.text.isEmpty {
VStack {
Text("Placeholder")
.multilineTextAlignment(.leading)
Spacer(minLength: 0)
}
}
TextEditor(text: $text)
.padding(.vertical, 20)
.padding(.horizontal, 36)
.opacity(self.text.isEmpty ? 0.1 : 1)
} //: Z
.frame(width: self.screenWidth, height: self.screenWidth * 0.583)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke()
.foregroundColor(.gray)
.padding(.horizontal, 16)
)
} //: V
}
}
@lucianoschillagi
Copy link

lucianoschillagi commented Feb 6, 2021

Suggestion:

struct TextEditorPlaceHolder: View {
    
    @State private var text: String = ""
    
    private let screenWidth = UIScreen.main.bounds.width
    
    var body: some View {
        
        VStack {
            
            ZStack(alignment: .leading) {
                
                if self.text.isEmpty {
                    VStack {
                        Text("Placeholder")
                            .padding(.leading, 25)
                            .padding(.top, 10)
                            .multilineTextAlignment(.leading)
                            .opacity(0.4)
                        
                        Spacer(minLength: 0)
                    }
                }
                
                TextEditor(text: $text)
                    .padding(.leading, 25)
                    .opacity(self.text.isEmpty ? 0.1 : 1)
            } //: Z
            .frame(width: self.screenWidth, height: self.screenWidth * 0.583)
            .overlay(
                RoundedRectangle(cornerRadius: 8)
                    .stroke()
                    .foregroundColor(.gray)
                    .padding(.horizontal, 16)
            )
        } //: V
    }
    
}

Thanks Aaron Lee!

@aaronlab
Copy link
Author

aaronlab commented Feb 6, 2021

@lucianoschillagi Thanks for your suggestion!

@dimpy-iroid
Copy link

dimpy-iroid commented Dec 27, 2023

I used the code, but my cursor is too transparent unlike in TextField. see the image how cursor is in light blue not like what we see in TextField's placeholder
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment