Home > AI > IOS > SwiftUI >

Show indicator on TabView

Example

struct ContentView: View {
    @State public var selectedTab = 0
    
    private var badgePosition: CGFloat = 2
    private var tabsCount: CGFloat = 2
    
    
    
    var body: some View {
        GeometryReader { geometry in
            
            ZStack(alignment: .bottomLeading) {
                
                TabView(selection: $selectedTab){
                    Text("HomeView")
                        .tabItem {
                            Image(systemName: (selectedTab == 0 ? "house.fill" : "house"))
                            Text("主页")
                        }.tag(0)
                  
                    Text("LiveView")
                        .tabItem {
                            Image(systemName: (selectedTab == 1 ? "video.fill" : "video"))
                            Text("直播")
                        }.tag(1)
                  
                    Text("MessageView")
                        .tabItem {
                            Image(systemName: (selectedTab == 2 ? "message.fill" : "message"))
                            Text("消息")
                        }.tag(2)
                  
                    Text("ContentView")
                        .tabItem {
                            Image(systemName: (selectedTab == 3 ? "eye.fill" : "eye"))
                            Text("关注")
                        }.tag(3)
                    
                    Text("OtherView")
                        .tabItem {
                            Image(systemName: (selectedTab == 3 ? "person.fill" : "person"))
                            Text("更多")
                        }.tag(4)
                }
                
                
                ZStack {
                    Circle()
                        .foregroundColor(.red)

                    Text("3")
                        .foregroundColor(.white)
                        .font(Font.system(size: 12))
                }
                .frame(width: 15, height: 15)
                .offset(x: ( ( 2 * self.badgePosition) - 0.95 ) * ( geometry.size.width / ( 5 * self.tabsCount ) ) + 2, y: -30)
                .opacity(1.0)
            
            
                ZStack {
                    Circle()
                        .foregroundColor(.red).frame(width: 8, height: 8)
                }
                .frame(width: 15, height: 15)
                .offset(x: ( (5 * self.badgePosition) - 0.95 ) * ( geometry.size.width / ( 5 * self.tabsCount ) ) + 2, y: -30)
                .opacity(1.0)
 
            } // ZStack
        } // GeometryReader
    }
}

Leave a Reply