SwiftUI - Animations triggered inside a View that's in a list doesn't animate the list as well

后端 未结 1 1476
北恋
北恋 2020-12-09 21:06

I have a List that\'s displaying two Views of the same type. When you tap on one of the views, they change their height with an animation.

相关标签:
1条回答
  • 2020-12-09 21:56

    The solution is just to make height animatable continuously, by providing explicit animatable modifier for this.

    Here is working approach. Tested with Xcode 11.4 / iOS 13.4.

    demo

    Implementation of simple helper modifier

    struct AnimatingCellHeight: AnimatableModifier {
        var height: CGFloat = 0
    
        var animatableData: CGFloat {
            get { height }
            set { height = newValue }
        }
    
        func body(content: Content) -> some View {
            content.frame(height: height)
        }
    }
    

    Modified using view (other parts unchanged)

    struct SubView: View {
        @State var change: Bool = false
    
        var body: some View {
            Rectangle()
                .frame(width: 200)
                .modifier(AnimatingCellHeight(height: change ? 300 : 200))
                .foregroundColor(Color.red)
                .onTapGesture {
                    withAnimation {
                        self.change.toggle()
                    }
                }
        }
    }
    
    0 讨论(0)
提交回复
热议问题