Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placeholder text color in TextField

Is it possible to change the placeholder text color in SwiftUI.TextField?

like image 403
Sergey Avatar asked Sep 21 '19 12:09

Sergey


People also ask

Can you change placeholder text color?

<input type="text" placeholder="A red placeholder text..">

What is the placeholder text color?

Note: In most browsers, the appearance of placeholder text is a translucent or light gray color by default.

How do I change the color of a placeholder?

You can change the Select placeholder color by using CSS. Use id only to change the color or placeholder and if you want to change the color of the option then use the option also.

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

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


Video Answer


1 Answers

SwiftUI doesn't support AttributedString and there is no direct for it (yet). BUT YOU CAN build a custom placeholder with a few lines of codes like this:

Use ZStack and implement a placeholder yourself:

var body: some View {
    ZStack(alignment: .leading) {
        if text.isEmpty {
            Text("Placeholder")
                .foregroundColor(.red)
        }
        TextField("", text: $text)
    }
}

So you can do any customization you like to the placeholder.

- Custom TextField (with placeholder)

You can always create your own custom Views to use everywhere:

struct CustomTextField: View {
    var placeholder: Text
    @Binding var text: String
    var editingChanged: (Bool)->() = { _ in }
    var commit: ()->() = { }

    var body: some View {
        ZStack(alignment: .leading) {
            if text.isEmpty { placeholder }
            TextField("", text: $text, onEditingChanged: editingChanged, onCommit: commit)
        }
    }
}

usage (TextField with placeholder):

struct ContentView: View {
    @State var text = ""

    var body: some View {
        CustomTextField(
            placeholder: Text("placeholder").foregroundColor(.red),
            text: $text
        )
    }
}
like image 172
Mojtaba Hosseini Avatar answered Nov 15 '22 05:11

Mojtaba Hosseini