Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI. How to change the placeholder color of the TextField?

Tags:

swift

swiftui

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?

like image 704
Ilya Kharabet Avatar asked Aug 28 '19 08:08

Ilya Kharabet


People also ask

How do I change the color of placeholder in TextField SwiftUI?

Just use . foregroundColor to change the text color of a TextField in SwiftUI.

How do I change the placeholder color on a storyboard?

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.

How do I change the placeholder color in Swift Searchbar?

Try this: UITextField *searchField = [searchbar valueForKey:@"_searchField"]; field. textColor = [UIColor redColor]; //You can put any color here.


1 Answers

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) } 

Demo1

💡 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:

Demo2

✅ If you are interested, Here is how to apply resizable gradient on any view


💡 The Art of the simplicity

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) }     } } 

Just like that 😉

like image 192
Mojtaba Hosseini Avatar answered Sep 30 '22 11:09

Mojtaba Hosseini