Home > Software engineering >  How to animate Form cell to [dis]appear?
How to animate Form cell to [dis]appear?

Time:01-17

I have the following:

struct HelloView
{
    @State private var name: String = ""

    var body: some View
    {
        NavigationStack
        {
            Form
            {
                Section
                {
                    TextField("Enter your name", text: $name)

                    if !name.isEmpty
                    {
                        Button("Save name")
                        {

                        }
                    }
                }
            }
        }
        .navigationTitle("Hello")
    }
}

When starting to enter the name, the button cell appears suddenly. How can this be animated?

This is a very similar question from 2019 that was never answered.

I'm on iOS 16. Can this be done?

CodePudding user response:

The following worked:

This will probably work (tested in iOS 16 in a similar situation):

  • Add @State private var isShowingButton = false
  • Replace if !name.isEmpty by if isShowingButton
  • Under .navigationTitle(...) add:
   onChange(of: name)
   { newValue in
       withAnimation { isShowingButton = newValue }
   }

But I'm wondering if there's no simpler solution.

  • Related