How to animate tabbar items (on selection) in SwiftUI?

后端 未结 2 1373
离开以前
离开以前 2021-02-08 05:25

How can I animate Tabbar Items (of a TabView) on selection in SwiftUI?

for example give the selected item a .scaleEffect() with .spring()

2条回答
  •  执笔经年
    2021-02-08 05:43

    Here is possible approach for standard TabView (for provided code snapshot).

    The idea is to use animatable modifier for font size over used SF images.

    Tested with Xcode 11.4 / iOS 13.4

    // Animating font size
    struct AnimatableSFImage: AnimatableModifier {
        var size: CGFloat
    
        var animatableData: CGFloat {
            get { size }
            set { size = newValue }
        }
    
        func body(content: Self.Content) -> some View {
            content
                .font(.system(size: size))
        }
    }
    
    // helper extension
    extension Image {
        func animatingSF(size: CGFloat) -> some View {
            self.modifier(AnimatableSFImage(size: size))
        }
    }
    
    // Modified test code snapshot
    struct TestAnimatedTabBar: View {
        @State var enlargeIt1 = false
        @State var enlargeIt2 = true
    
        var body: some View {
            TabView {
                Text("Item 1")
                    .onAppear {
                        self.enlargeIt1.toggle()
                        self.enlargeIt2.toggle()
                    }
                    .tabItem{
                        VStack{
                            Image(systemName: "music.note")
                                .animatingSF(size: self.enlargeIt1 ? 30 : 15 )
                            Text("Music")
                        }.animation(.interpolatingSpring(mass: 0.7, 
                 stiffness: 200, damping: 10, initialVelocity: 4))
                    }.tag(1)
    
                Text("Item 2")
                    .onAppear {
                        self.enlargeIt1.toggle()
                        self.enlargeIt2.toggle()
                    }
                    .tabItem{
                        VStack{
                            Image(systemName: "music.mic")
                                .animatingSF(size: self.enlargeIt2 ? 30 : 15 )
                            Text("Mic")
                        }.animation(.interpolatingSpring(mass: 0.7, 
                 stiffness: 200, damping: 10, initialVelocity: 4))
                    }.tag(2)
    
            }
        }
    }
    

提交回复
热议问题