SwiftUI: Add ClearButton to TextField

前端 未结 5 598
长发绾君心
长发绾君心 2021-02-07 22:46

I am trying to add a ClearButton to TextField in SwiftUI when the particular TextField is selected.

The closest I got was creating a ClearButton ViewM

5条回答
  •  难免孤独
    2021-02-07 23:06

    public struct ClearButton: ViewModifier {
        @Binding var text: String
    
        public init(text: Binding) {
            self._text = text
        }
    
        public func body(content: Content) -> some View {
            HStack {
                content
                Spacer()
                // onTapGesture is better than a Button here when adding to a form
                Image(systemName: "multiply.circle.fill")
                    .foregroundColor(.secondary) 
                    .opacity(text == "" ? 0 : 1)
                    .onTapGesture { self.text = "" }
            }
        }
    }
    

    Usage:

    @State private var name: String
    
    ...
    
    Form {
        Section() {
            TextField("NAME", text: $name).modifier(ClearButton(text: $name))
        }
    }
    

提交回复
热议问题