7

How I can disable button if a text field is empty for Swift UI. My code:

struct AddTask: View {
  @Binding var isOpen: Bool
  @State var text = ""
  let tint: Color
  let done: (String) -> ()

  var body: some View {
    VStack() {
      HStack {
        Text("What tasks are you planning to do?")
          .font(.custom("Avenir", size: 14))
          .foregroundColor(.gray)
        Spacer()
      }

        CustomTextField(text: $text, isFirstResponder: true)
        .frame(height: 30)

      HStack {
        Spacer()
        Button(action: { self.done(self.text); self.isOpen.toggle() }) { Text("Done") }
          .foregroundColor(self.tint)
      }
      Spacer()
    }
    .padding(.all, 30)
  }
}

I want to disable button if CustomTextField is empty.

1 Answer 1

11

Use .disabled modifier like in following

    Button(action: { self.done(self.text); self.isOpen.toggle() }) { Text("Done") }
      .foregroundColor(self.tint)
      .disabled(self.text.isEmpty)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.