Floating Tabbar in SwiftUI

Faizan Naseem
3 min readJan 27, 2021

--

In this article i will show you how to create a floating Tabbar in SwiftUI 2.0. At the end of this article it will look something like this.

First i will take a default tabbar and hide it so that i can a custom one. It will look something like this.

Then i will wrap the tabbar in Zstack and add the alignment centre and bottom so that i can create custom bar on it.

To create custom tab bar i have just added buttons on loop and put on Hstack and give padding and background colour into it. Also on each button action i am changing the selected state. If you run the app it will work like a normal tabbar.

Next i will create a custom shape so that on tap of each button it animates and changes its x position. Create a struct called CustomShape and extend it from Shape protocol.

There is a property call animatableData, SwiftUI will set the animatableData property of our shape to the latest value, and it’s down to us to decide what that means – in our case we assign it directly to xAxis, because that’s the thing we want to animate.

Next in for loop i will wrap each button into GeometryReader so basically what GeometryReader does is let us read the size that was proposed by the parent. So in our case on tap of each button it will change the tabbar state also xaxis value of our custom shape so that it could animate. Also i updated Hstack background colour with our custom shape. Sample code will look like this.

If you run the app you will notice the two things. On start of app the first shape is not in right place because on top xAxis = 0 so we need to change its position when the whole view is load for first time and second we need to change the Offset of selected button image.

To resolve first issue i have added OnAppear closure on each button basically OnAppear triggers `action` when this button appears. So i put a condition if selected image is the first tab array element update xAxis position with its geometry reader. To resolve second issue i have just updated x and y offset when current button image is selected. Final code will be look like this.

Conclusion

So this is how you can create a floating tabbar in SwiftUI without integration of any third party library. 😁😁

Thank you for your attention and time!

--

--