Vlad Poncea
Vlad Poncea

Reputation: 359

Can I somehow convert Binding<String> to String?

I am trying to call a function that looks like this

func customTextField(placeholder: String, text: Binding<String>) -> some View {
        ZStack(alignment: .leading){
            if text.isEmpty{
                VStack {
                    Text(placeholder)
                        .font(.system(size: 14))
                        .fontWeight(.regular)
                        .foregroundColor(Color(red: 0.5803921568627451, green: 0.5803921568627451, blue: 0.5803921568627451))
                        .padding()
                    
                    if placeholder == "Your message type here..."{
                        Spacer()
                    }
                }
            }
            
            TextField("", text: text)
                .font(.system(size: 14))
                .foregroundColor(.black)
                .padding()
            
        }
        .frame(height: placeholder == "Your message type here..." ? 170 : 54)
        .background(RoundedRectangle(cornerRadius: 16).stroke(text.isEmpty ? Color.clear : Color("orange")))
        .background(Color.white)
        .cornerRadius(16)
    }

But as text is a Binding<String> I can't use .isEmpty() on it. I don't want to create another struct view for it. What would be the best approach for this?

Upvotes: 5

Views: 4743

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

You simply need to call wrappedValue on a Binding to access its underlying value, there's no need for any type conversion.

So do

text.wrappedValue.isEmpty

instead of

text.isEmpty

Upvotes: 16

Related Questions