Move To Top of Tab on selecting same tab from Tab Bar in SwiftUI
The popularity of SwiftUI is increasing every day. It is good to have that in our iOS development stack.
This article is to build one of common features we come across in many popular iOS Apps like WhatsApp. The feature is when we tap on same selected tab from tab bar, If we are not on top of that selected tab then we will be moved to top.
Let’s build this popular feature in SwiftUI. Also this can be easily customised to moving anywhere in selected tab with just a click.
Implementation
We will use a simple view which we will display as first tab consisting of list of 40 items and a header.
FirstTabView displays list of 40 items with a header. This view is very simple having a list wrapped inside ScrollViewReader to scroll to the particular position.
The position can be decided by identity of view. We know that each view in SwiftUI is made up of many views and every view has its own identity in SwiftUI. If we look at ForEach loop, we pass id as \.self. So each view inside list of 40 views has unique identity specified there. To understand more about identity, please refer to this article.
Also, other than structural identity, we can assign a custom identity to a view explicitly with .id() as shown in line number 9.
This identity is used to scroll to particular view using “proxy.scrollTo(<identity of view>)”
We used a binding boolean variable to detect tap on selected tab. When there was change in binding variable, we scroll to header i.e., top of tab. Similarly the identity of view placed any where like bottom or middle of entire view can be given.
Main Tab View
Let us build the final Tab View where we change binding boolean passed to our FirstTabView.
We use StateObject of TabStateHandler to observe selection of tabs and moveFirstTabToTop boolean variable which we used in FirstTabView.
When selected tab is first stab and selected tab is same as already selected tab then change the state of boolean variable which executes logic we written inside .onChange(of:) inside FirstTabView.
That’s it!!
Thanks for reading:))