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

后端 未结 2 1375
离开以前
离开以前 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:39

    Someone created a custom TabView that might be of help to you. I'm sure you could modify it to suit your needs.

    BottomBar component for SwiftUI inspired by this concept

    https://github.com/smartvipere75/bottombar-swiftui

    import SwiftUI
    import BottomBar_SwiftUI
    
    let items: [BottomBarItem] = [
        BottomBarItem(icon: "house.fill", title: "Home", color: .purple),
        BottomBarItem(icon: "heart", title: "Likes", color: .pink),
        BottomBarItem(icon: "magnifyingglass", title: "Search", color: .orange),
        BottomBarItem(icon: "person.fill", title: "Profile", color: .blue)
    ]
    
    struct BasicView: View {
        let item: BottomBarItem
    
        var detailText: String {
        "\(item.title) Detail"
    }
    
    var followButton: some View {
        Button(action: openTwitter) {
            VStack {
                Text("Developed by Bezhan Odinaev")
                    .font(.headline)
                    .color(item.color)
    
                Text("@smartvipere75")
                    .font(.subheadline)
                    .foregroundColor(.gray)
            }
        }
    }
    
    var destination: some View {
        Text(detailText)
            .navigationBarTitle(Text(detailText))
    }
    
    var navigateButton: some View {
        NavigationLink(destination: destination) {
            ZStack {
                Rectangle()
                    .fill(item.color)
                    .cornerRadius(8)
                    .frame(height: 52)
                    .padding(.horizontal)
    
                Text("Navigate")
                    .font(.headline)
                    .foregroundColor(.white)
            }
        }
    }
    
    func openTwitter() {
        guard let url = URL(string: "https://twitter.com/smartvipere75") else {
            return
        }
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
    
    var body: some View {
        VStack {
            Spacer()
    
            followButton
    
            Spacer()
    
            navigateButton
            }
        }
    }
    
    struct ContentView : View {
        @State private var selectedIndex: Int = 0
    
        var selectedItem: BottomBarItem {
            items[selectedIndex]
        }
    
        var body: some View {
            NavigationView {
                VStack {
                    BasicView(item: selectedItem)
                        .navigationBarTitle(Text(selectedItem.title))
                    BottomBar(selectedIndex: $selectedIndex, items: items)
                }
            }
        }
    }
    

提交回复
热议问题