Anan R
Anan R

Reputation: 311

SwiftUI: Clear TextField on edit begin

How can I clear the content of TextField when editing begin.

I've try to read Apple Document and search all the similar question and cannot find the answer.

Upvotes: 7

Views: 6965

Answers (2)

Marc T.
Marc T.

Reputation: 5320

In code it would look like this:


import SwiftUI
import PlaygroundSupport

struct MyTextView: View {
    @State private var text1: String = "Some Content"
    @State private var text1Placeholder: String = ""
    @State private var text2: String = ""
    var body: some View {
        VStack(alignment: HorizontalAlignment.center, spacing: 20) {

            Image(systemName: "circle")
            TextField( self.$text1Placeholder.wrappedValue, text: $text1, onEditingChanged: { (editing) in
                if editing {
                    self.$text1Placeholder.wrappedValue
                        = self.$text1.wrappedValue 
                    self.$text1.wrappedValue = ""
                }
            })
            TextField("Text Field 2", text: $text2)
            .border(Color.green)

        }.padding()

    }
}

PlaygroundPage.current.liveView = UIHostingController(rootView: MyTextView())

Upvotes: 6

Michael Salmon
Michael Salmon

Reputation: 1184

The onEditingChange parameter take a closure with a single Bool parameter, if it is true then the TextField has begun to edit the parameter. In your closure check the value of the parameter and clear the TextField variable if it is true.

Upvotes: 2

Related Questions