Home > AI > IOS > SwiftUI >

How to add a clear button to the TextField

Source: https://sanzaru84.medium.com/swiftui-how-to-add-a-clear-button-to-a-textfield-9323c48ba61c

struct TextFieldClearButton: ViewModifier {
    @Binding var text: String
    
    func body(content: Content) -> some View {
        HStack {
            content
            
            Button(
                action: { self.text = "" },
                label: {
                    Image(systemName: "delete.left")
                        .foregroundColor(Color(UIColor.opaqueSeparator))
                }
            )
        }
    }
}
TextField(home.userNickname, text: $home.userNickname)
                .modifier(TextFieldClearButton(text: $home.userNickname))
                .padding()
                .background(Color.white)

Leave a Reply