Skip to content

Instantly share code, notes, and snippets.

@hira22
Last active December 3, 2021 08:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hira22/b39594919cf516dbfe33f3b53cd804f3 to your computer and use it in GitHub Desktop.
Save hira22/b39594919cf516dbfe33f3b53cd804f3 to your computer and use it in GitHub Desktop.
SwiftUI TextEditor にプレースホルダーを設定する
import SwiftUI
struct PlaceHolderTextEditor: View {
var placeholderText: String
@State var text: String
var body: some View {
ZStack(alignment: .topLeading) {
if text.isEmpty {
Text(placeholderText)
.foregroundColor(Color(UIColor.placeholderText))
.padding(.leading, 5)
.padding(.top, 24)
}
TextEditor(text: $text)
.padding(.top)
}
.onAppear() {
//⚠️ NOTE: UITextView の backgroundColor を変更しておかないと、placeholderText が表示されない
UITextView.appearance().backgroundColor = .clear
}
.onDisappear() {
UITextView.appearance().backgroundColor = nil
}
}
}
import SwiftUI
@main
struct PlaceHolderTextEditorSampleApp: App {
var body: some Scene {
WindowGroup {
PlaceHolderTextEditor(placeholderText: "Placeholder Text", text: "")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment