Yhondri
Yhondri

Reputation: 944

SwiftUI - How do I change the text color of a Textfield?

I'm trying to change the textcolor of Textfield (the text that user write) in SwiftUI. I'm trying with foregroundColor but it changes the placeholder's text color.

How do you do this in SwiftUI?

 TextField($variable, placeholder: Text("a text"))
            .foregroundColor(.green)

Upvotes: 39

Views: 78795

Answers (4)

Kyle Clegg
Kyle Clegg

Reputation: 39470

In Xcode 16 foregroundColor will be deprecated and replaced with foregroundStyle e.g.

Text("Hello World").foregroundStyle(.black)

Upvotes: 0

Steve Yuan
Steve Yuan

Reputation: 81

Use background() to set background color and foreground() to set input text color

struct PlaygroundTestView: View {
    
    @State var searchText = ""
    
    var body: some View {
        
        TextField("Search", text: $searchText)
        .font(Font.system(size: 14))
        .padding()
        .background(RoundedRectangle(cornerRadius: 50).fill(Color.white))
        
        .foregroundColor(.black)
        .padding()
        .offset(x:8, y: 10)
    }
}

Upvotes: 7

Srinivasan_iOS
Srinivasan_iOS

Reputation: 1078

Text color should be changed for using the Property of text field .foreground color Updated for Xcode Version 11.1 (11A1027)

SwiftUI

TextField("Email", text: $email)
                .textContentType(.emailAddress)
                .padding(.init(top: 0, leading: 15, bottom:0 , trailing: 15))
                .foregroundColor(.blue)
                .textFieldStyle(RoundedBorderTextFieldStyle.init())

Upvotes: 2

M Reza
M Reza

Reputation: 19708

.foregroundColor actually does change the text color of TextField but only when it has a default value, for example this will work fine:

TextField(.constant("Hello World"), placeholder: Text("Type here..."))
  .foregroundColor(.green)

But once you remove the whole text, text field loses not only its color but the rest of its modifiers such as its alignment as well. This is likely a bug in the current version so I'll file a bug report.


Update: This issue was fixed with Xcode 11 beta 3.

Upvotes: 50

Related Questions