How to build custom TabBar using SwiftUI?

Demo -Image

Implementation Logic

  • Build Bottom Bar HStack UI with tab Item
  • Move/Translate selected tab up on Tap
  • Draw Bar path as curve around selected Indes

First we create a tab Item object which contains Tab Icon name and the relative offset.

class TabItem: Identifiable {
let id = UUID()
let imageName: String
var offset: CGFloat = -5
var opacity: Double = 1

init(imageName: String, offset: CGFloat) {
self.imageName = imageName
self.offset = offset
}
init(imageName: String) {
self.imageName = imageName
}
}

Create a ObservableObject to help update selected index.

class TabItems: ObservableObject {
@Published var items: [TabItem] = [
TabItem(imageName: "house", offset: -20),
TabItem(imageName: "magnifyingglass"),
TabItem(imageName: "plus.app"),
TabItem(imageName: "heart"),
TabItem(imageName: "person"),
]
@Published var selectedTabIndex: CGFloat = 1
func select(_ index: Int) {
let tabItem = items[index]

tabItem.opacity = 0
tabItem.offset = 15

withAnimation(Animation.easeInOut) {
selectedTabIndex = CGFloat(index + 1)
for i in 0..<items.count {
if i != index {
items[i].offset = -5
}
}
}
withAnimation(Animation.easeOut(duration: 0.25).delay(0.25)) {
tabItem.opacity = 1
tabItem.offset = -25
}
}
}

Now, Create HStack with in VStack with Spacer on top to move the view below.

Also, We calculate the position of every tab Item to create curve on select.

Using firstCenter and stepperToNextCenter, we create a curve to the selected index

Complete Code:

iOS Developer | Swift | Flutter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store