반응형

아직까지 SwiftUI의 TextField에는 기본적으로 clearButton이 제공되지 않아서 직접 해당 버튼을 추가해야 합니다. 
다음과 같이 ViewModifier를 이용하면 편하게 사용할 수 있습니다

struct ClearButton: ViewModifier {
    @Binding var text: String
    
    func body(content: Content) -> some View {
        HStack {
            content
            if !text.isEmpty {
                Button {
                    text = ""
                } label: {
                    Image(systemName: "multiply.circle.fill")
                        .foregroundColor(.gray)
                }
                .padding(.trailing, 8)
            }
        }
    }
}

extension View {
    func clearButton(text: Binding<String>) -> some View {
        modifier(ClearButton(text: text))
    }
}

// How to use
TextField("", text: $text)
  .clearButton(text: $text)
  .padding(8)
  .overlay(RoundedRectangle(cornerRadius: 8).stroke(.blue, lineWidth: 1))
  .padding(.horizontal, 12)

반응형
Posted by 까칠코더
,