Search code examples
textswiftuiplaceholderrestore

How to restore placeholder text when TextField is cleared


I'm having an issue restoring the placeholder text on a TextField when the TextField has been cleared.

Are there any less hacky ways of restoring the text other than what I've found here?

Clearing SwiftUI TextField will not restore placeholder

Cheers, Oliver


Solution

  • Fixed in iOS 15

    *consider below for old versions support only


    As I wrote in that other topic it is current SwiftUI defect, so for now only workaround is possible.

    Here is a simple one that works for me (I prefer this approach because it remains valid even after some fixes/changes in the area):

    @State private var text: String = ""
    @State private var refresh = false
    
    var body: some View {
        VStack {
            TextField("Placeholder" + (refresh ? "" : " "), text: $text)
            Divider()
            Button("Clear") {
                self.text = ""
                self.refresh.toggle() // << force refresh placeholder explicitly
            }
        }
    }