Theoutsider
Theoutsider

Reputation: 83

Swift UI: Disable a button if a text field is empty and contains whitespace

I'm looking for a solution to disable a button if the textfield is empty or contain only empty space. I use .disabled on a character count but it's not avoiding empty space.

                Button(action: sendComment) {
                Image(systemName: "paperplane.fill")
                    .frame(width:50, height: 30)
                    .foregroundColor(.white)
                    .background(
                        LinearGradient(
                            gradient: Gradient(
                                colors: [
                                    Color("Red1"),
                                    Color("Red2")
                                ]
                            ),
                            startPoint: .topTrailing,
                            endPoint: .bottomLeading
                        )
                    )
                    .cornerRadius(20)
                    .padding(.trailing)
            }
            .disabled(comment!.count == 0)

Upvotes: 0

Views: 897

Answers (1)

Gustavo Conde
Gustavo Conde

Reputation: 977

Have you tried removing the whitespaces? Something like

Button(action: sendComment) {
            Image(systemName: "paperplane.fill")
                .frame(width:50, height: 30)
                .foregroundColor(.white)
                .background(
                    LinearGradient(
                        gradient: Gradient(
                            colors: [
                                Color("Red1"),
                                Color("Red2")
                            ]
                        ),
                        startPoint: .topTrailing,
                        endPoint: .bottomLeading
                    )
                )
                .cornerRadius(20)
                .padding(.trailing)
        }
        .disabled(comment!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)

Upvotes: 2

Related Questions