TextField のプレースホルダーの色を変更したいのですが、その方法が見つかりません。
foregroundColor
と を設定してみましたaccentColor
が、プレースホルダーの色は変わりません。
コードは次のとおりです:
TextField("Placeholder", $text)
.foregroundColor(Color.red)
.accentColor(Color.green)
おそらくこれに対する API はまだ存在しないのでしょうか?
ベストアンサー1
iOS 15から
prompt
の引数を使用できますTextField
:
TextField("", text: $text, prompt: Text("Placeholder"))
iOS 15未満
あらゆる外観を持つすべての iOS バージョンをサポートするカスタム プレースホルダー:
カスタムplaceholder
修飾子を使用して表示する任意のビューの所有者としてその他のビュー! 例:
TextField("", text: $text)
.placeholder(when: text.isEmpty) {
Text("Placeholder recreated").foregroundColor(.gray)
}
ZStack
�� 次のような拡張機能を簡単に使用できますView
。
extension View {
func placeholder<Content: View>(
when shouldShow: Bool,
alignment: Alignment = .leading,
@ViewBuilder placeholder: () -> Content) -> some View {
ZStack(alignment: alignment) {
placeholder().opacity(shouldShow ? 1 : 0)
self
}
}
}
上記の方法は、どれでも、、、などのView
ようなものです。TextField
TextEditor
Image
�� ボーナス:完全なカスタマイズ!
拡張アプローチでは、どれでも次のような画像付きグラデーション プレースホルダーのようなプレースホルダーにスタイルを適用します。
✅ ご興味がございましたら、こちらをご覧ください任意のビューにサイズ変更可能なグラデーションを適用する方法
�� シンプルさの芸術
ほとんどの場合、次のように文字列と灰色のプレースホルダーを渡すだけで済みます。
TextField("", text: $text)
.placeholder("Placeholder", when: text.isEmpty)
上記の拡張機能の周りに簡単なラッパーを書くことができます:
extension View {
func placeholder(
_ text: String,
when shouldShow: Bool,
alignment: Alignment = .leading) -> some View {
placeholder(when: shouldShow, alignment: alignment) { Text(text).foregroundColor(.gray) }
}
}