acerblaze
acerblaze

Reputation: 21

How to properly clear TextField on submit in SwiftUI?

I want to log some text and clear the TextField after submitting without changing the value of the logged text. How I can achieve that?

Here's example of my code:

@State private var loggedText: String = ""
@State private var showLoggedText = false

var body: some View {
    
    VStack {
        
        if showLoggedText {
            Text(loggedText)
        }
            
            HStack {
                TextField(
                       "Add new set",
                       text: $loggedText
                   )
                .onSubmit {
                    showLoggedText = true
                    loggedText = ""
                }
            }
    }

Upvotes: 1

Views: 2699

Answers (1)

Soulfire J. Backblaze
Soulfire J. Backblaze

Reputation: 85

Going off one of the comments. It seems as though that you need to assign loggedText to another variable like so:

@State private var loggedText: String = ""
@State private var showLoggedText = false

var body: some View {
    
    VStack {
        
        if showLoggedText {
            Text(loggedText)
        }
            
            HStack {
                TextField(
                       "Add new set",
                       text: $loggedText
                   )
                .onSubmit {
                    showLoggedText = true
                    newText = loggedText
                }
            }
    }

This will allow you to submit the text without it being cleared. The loggedText = "" clears everything that you had. Keep in mind that this code won't "lock" whatever's in loggedText. If you change the field after submitting. The text will be updated again.

Upvotes: 1

Related Questions