swiftmacosswiftuitextfieldnstextfield

Change Textfield placeholder color in SwiftUI on macOS


I am trying to set the placeholder color of a Textfield on macOS. I tried:

TextField("", text: $text, prompt: Text("prompt"))
                    .tint(.red)

but that does not seem to get respected.

.accentColor is deprecated (and doesn't work), .foregroundStyle does not affect it (no matter if I put it outside the texfield or directly on the prompt), .colorMultiply is not correct as it applies to the entire field and it's a blending mode, not a setting of an individual color (it makes everything the color you set it to).

I tried to do a custom styling by subclassing TextFieldStyle but couldn't find any modifier that would affect it.

Do I need to resort to a custom NSViewRepresentable and AppKit? I thought SwiftUI would support these features by now. Maybe I'm missing something.

I also have the same problem with the caret color.


Solution

  • You could always show the prompt as an overlay. Then you can style it any way you like:

    TextField("", text: $text)
        .overlay(alignment: .leading) {
            if text.isEmpty {
                Text("prompt")
                    .foregroundStyle(.red)
                    .padding(.leading, 4)
                    .allowsHitTesting(false)
            }
        }
    

    The caret adopts the color defined as AccentColor in the asset catalog. But of course, this is used in a lot of other places too.