I want to change the placeholder color of the TextField, but I can't find a method for it.
I tried to set foregroundColor
and accentColor
, but it doesn't change the placeholder color.
Here is the code:
TextField("Placeholder", $text) .foregroundColor(Color.red) .accentColor(Color.green)
Maybe there is no API for this yet?
Just use . foregroundColor to change the text color of a TextField in SwiftUI.
The easiest method to modify the placeholder text color is through the Xcode storyboard interface builder. Select the UITextField of interest and open the identity inspector on the right. Click on the plus symbol in the User Defined Runtime Attributes and add a new row with Key Path as placeholderLabel.
Try this: UITextField *searchField = [searchbar valueForKey:@"_searchField"]; field. textColor = [UIColor redColor]; //You can put any color here.
There is no api for it (yet). BUT YOU CAN:
Use a custom placeholder
modifier to show any view as the holder of any other view! e.g:
TextField("", text: $text) .placeholder(when: text.isEmpty) { Text("Placeholder recreated").foregroundColor(.gray) }
💡 It's a simple ZStack
that you can in a View
extension like:
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 } } }
🎁 Now you can apply any kind of style to the placeholder like this gradient placeholder with image:
✅ If you are interested, Here is how to apply resizable gradient on any view
Most of the time you need to pass just a string and a gray placeholder like:
TextField("", text: $text) .placeholder("Placeholder", when: text.isEmpty)
you can write a simple wrapper around the above extension for it:
extension View { func placeholder( _ text: String, when shouldShow: Bool, alignment: Alignment = .leading) -> some View { placeholder(when: shouldShow, alignment: alignment) { Text(text).foregroundColor(.gray) } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With