SwiftUI tip: Tab bar with rounded corners and shadow
2 min readSep 25, 2023
Customizing TabView
in SwiftUI can be trick sometimes and at some point you may want to add rounded corners with shadow.
If you try to add the shadow as a sublayer you may end up with the shadow layer covering the content behind it like below:
So instead of using a sublayer here we will be using another view that will be responsible for adding the shadow but with `masksToBounds` as `false`.
In the below setup I have the built-in TabView
component from SwiftUI (with custom font, colors, etc) and the extension to customize it. Take a look below how to combine corner radius with shadow in a simple way.
extension UITabBarController {
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tabBar.layer.masksToBounds = true
tabBar.layer.cornerRadius = 16
// Choose with corners should be rounded
tabBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] // top left, top right
// Uses `accessibilityIdentifier` in order to retrieve shadow view if already added
if let shadowView = view.subviews.first(where: { $0.accessibilityIdentifier == "TabBarShadow" }) {
shadowView.frame = tabBar.frame
} else {
let shadowView = UIView(frame: .zero)
shadowView.frame = tabBar.frame
shadowView.accessibilityIdentifier = "TabBarShadow"
shadowView.backgroundColor = UIColor.white
shadowView.layer.cornerRadius = tabBar.layer.cornerRadius
shadowView.layer.maskedCorners = tabBar.layer.maskedCorners
shadowView.layer.masksToBounds = false
shadowView.layer.shadowColor = Color.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 0.0, height: -8.0)
shadowView.layer.shadowOpacity = 0.3
shadowView.layer.shadowRadius = 10
view.addSubview(shadowView)
view.bringSubviewToFront(tabBar)
}
}
}
Final result: