SwiftUI TextField: Placeholder and Custom Color


Notice in the previous example when we applied foregroundColor modifier, it didn’t have any effect on placeholder text. Reason is that placeholder text is not customizable at this point so in order to customize placeholder text, we will have to come up with our own solution.

We can put a custom control together with the help of ZStack and observe the value in the binding variable. If the value in the binding variable is empty we will display Text view otherwise we will display TextField.
struct TextFieldExample: View {
    
    @State private var title: String = ""
    @State private var category: String = ""
    @State private var type: String = ""
    
    var body: some View {
        VStack {
            Text("DevTechie Courses")
                .font(.largeTitle)
            
            VStack(alignment: .leading) {
                Text("Enter new course title")
                    .font(.title3)
                
                ZStack(alignment: .leading) {
                    if title.isEmpty {
                        Text("Course title")
                            .bold()
                            .foregroundColor(Color.purple.opacity(0.4))
                    }
                    TextField("", text: $title)
                }
                .padding(.horizontal, 10)
                .padding(.vertical, 4)
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(Color.purple, lineWidth: 1)
                )
                    
                ZStack(alignment: .leading) {
                    if category.isEmpty {
                        Text("Course category")
                            .bold()
                            .foregroundColor(Color.teal.opacity(0.4))
                    }
                    TextField("", text: $category)
                }
                .padding(.horizontal, 10)
                .padding(.vertical, 4)
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(Color.teal, lineWidth: 1)
                )
                    
                ZStack(alignment: .leading) {
                    if type.isEmpty {
                        Text("Course type")
                            .bold()
                            .foregroundColor(Color.pink.opacity(0.4))
                    }
                    TextField("", text: $type)
                }
                .padding(.horizontal, 10)
                .padding(.vertical, 4)
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(Color.pink, lineWidth: 1)
                )
                
            }.padding(.top, 20)
        }.padding()
    }
}