Home > Software engineering >  Add top shadow to TabView in SwiftUI
Add top shadow to TabView in SwiftUI

Time:05-15

I have the following:

enter image description here

I'm using a native TabView. I can change the background but I haven't been able to add a little shadow to the top of the UITabBar, I've tried creating a function and onAppear calling it like this:

func setupTabBar() {
//        UITabBar.appearance().barTintColor = UIColor(named: "tabBarBackground")
//        UITabBar.appearance().scrollEdgeAppearance = UITabBarAppearance()
    
    UITabBar.appearance().backgroundColor = UIColor(named: "ThemeBackground2")
    UITabBarAppearance().shadowColor = .white
}

which works for the background but not the top line that I need.

Here's the basic TabView:

TabView(selection: $selectedTab) {
        MarketsTabBarView()
            .tag(HostingBarCategories.market)
            .tabItem {
                Image(systemName: "chart.xyaxis.line")
                Text("Market")
            }
        
        PortfolioTabBarView()
            .tag(HostingBarCategories.portfolio)
            .tabItem {
                Image(systemName: "bitcoinsign.square.fill")
                Text("Portfolio")
            }
            
        SettingsTabBarView()
            .tag(HostingBarCategories.settings)
            .tabItem {
                Image(systemName: "gearshape.fill")
                Text("Settings")
            }
}

How can I add a shadow on top to mark that separetion?

CodePudding user response:

The shadowColor is applied to default tab shadow which is currently absent, so we need a custom template image (eg. with gradient transparency) so shadowColor would tint it.

Here is working approach (Xcode 13.3 / iOS 15.4)

demo

Main part:

appearance.shadowColor = .white
appearance.shadowImage = UIImage(named: "tab-shadow")?.withRenderingMode(.alwaysTemplate)

Complete findings and code

  • Related