SwiftUI: Add ClearButton to TextField

前端 未结 5 592
长发绾君心
长发绾君心 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 22:48

    You can add another Binding in your modifier:

    @Binding var visible: Bool
    

    then bind it to opacity of the button:

    .opacity(visible ? 1 : 0)
    

    then add another State for checking textField:

    @State var showClearButton = true
    

    And lastly update the textfield:

    TextField("Some Text", text: $someBinding, onEditingChanged: { editing in
        self.showClearButton = editing
    }, onCommit: {
        self.showClearButton = false
    })
    .modifier( ClearButton(text: $someBinding, visible: $showClearButton))
    

提交回复
热议问题