简体   繁体   中英

How to make tabbar appearance non-transparent in SwiftUI, without tapping in UIKit properties?

UITabBar.appearance().isTranslucent = false

I can do this thing in swiftui controller's init method, but I want to use swiftui code to perform the same action, instead of UIKit code.

you could do a custom tabbar and customize anything you want

First: Create the model

struct TabItem: Identifiable {
    var id = UUID()
    var text: String
    var icon: String
    var tab: Tab
}

var tabItems = [
    TabItem(text: "Home", icon: "house", tab: .home),
    TabItem(text: "Serach", icon: "magnifyingglass", tab: .explore),
    TabItem(text: "Notifications", icon: "bell", tab: .notifications),
]

enum Tab: String {
    case home
    case explore
    case notifications
    case library
}

Second: Apply tab bar

struct ContentView: View {
    @State var selectedTab: Tab = .home
    
    var body: some View {
        ZStack(alignment: .bottom) {
            
            Group {
                switch selectedTab {
                case .home:
                    Text("First View")
                case .explore:
                    Text("Second View")
                case .notifications:
                    Text("Third View")
                case .library:
                    Text("Fourth View")
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            
            HStack {
                ForEach(tabItems) { item in
                    Button {
                        selectedTab = item.tab
                    } label: {
                        VStack(spacing: 0) {
                            Image(systemName: item.icon)
                                .symbolVariant(.fill)
                                .font(.body.bold())
                                .frame(width: 44, height: 29)
                            Text(item.text)
                                .font(.caption2)
                                .lineLimit(1)
                        }
                        .frame(maxWidth: .infinity)
                    }
                    .foregroundStyle(selectedTab == item.tab ? .primary : .secondary)
                }
            }
            .padding(.horizontal, 8)
            .padding(.top, 14)
            .frame(height: 88, alignment: .top)

            .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 0, style: .continuous))
            .frame(maxHeight: .infinity, alignment: .bottom)
            .ignoresSafeArea()
        }
    }
}

now the tab bar style is transparent thanks to ultraThinMaterial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM