Home > Net >  Toggle View Height with transition / animation
Toggle View Height with transition / animation

Time:01-04

i want to toggle the height of a view when I press a button. I tried several things:

  1. Button with transition (but I think this solution isn't good)
  2. A Slider which one changes the height (like I want it, but I want to toggle between two values)

Here my current Swift File:

import SwiftUI

struct TextView2: View {
    @State private var ChangeFrame2 = false
    @State private var height: Double = 200
    
    var body: some View {
        
        if ChangeFrame2 {
            Text("Hello, world!")
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 400)
                .font(.largeTitle)
                .foregroundColor(.white)
                .background(Color.red)
                .transition(.move(edge: .top))
        } else {
            Text("Hello, world!")
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: height)
                .font(.largeTitle)
                .foregroundColor(.white)
                .background(Color.green)
                .transition(.move(edge: .top))
        }
        
        Button("Press to show details") {
            withAnimation(.easeInOut(duration: 1.00)) {
                ChangeFrame2.toggle()
            }
    }
        
        Slider(value: $height, in: 10...500)
        Text("\(height, specifier: "%.0f") Height")
        
}
}

I also tried the following:

.background(ChangeFrame2 ? (maxHeight: 400) : (maxHeight: 600))

but it doesn't work. Thank you :)

CodePudding user response:

You can just have one Text view, using the ternary operator to decide the height and background color.

The problem is that when you use if, the two views now have different identities which breaks animations. You also have an unwanted move transition.

Code:

struct TextView: View {
    @State private var changeFrame = false
    @State private var height: Double = 200

    var body: some View {
        VStack {
            Text("Hello, world!")
                .frame(height: changeFrame ? 400 : height)
                .frame(maxWidth: .infinity)
                .font(.largeTitle)
                .foregroundColor(.white)
                .background(changeFrame ? Color.red : Color.green)

            Button("Press to show details") {
                withAnimation(.easeInOut(duration: 1)) {
                    changeFrame.toggle()
                }
            }

            Slider(value: $height, in: 10...500)

            Text("\(height, specifier: "%.0f") Height")
        }
    }
}

Result:

Result

  •  Tags:  
  • Related