SwiftUI and WatchOS: Action Buttons Beneath the Navigation Bar
Update your watchOS app to meet the new Apple guidelines
As we all know, the introduction of watchOS 7 has killed the force touch. In fact, in versions of watchOS before watchOS 7, people could press firmly on the display to open a hidden menu of actions relevant to the current screen.
Now Apple suggests removing hidden menus from our app, examining each item to determine whether it provides information, or it performs an action.
In their Human Interface Guidelines, they provide some alternatives for actionable items. One of them is putting an action button beneath the navigation bar.
In this design, people drag down to reveal the button. Even though such a button isn’t visible when the screen first opens, people can discover it easily because dragging is a very common gesture. For example, Mail relocates the Compose button from a hidden menu to a position above the list of messages in an inbox. The Compose button is out of the way until people drag down on the screen to refresh the message list.
In this article, we are going to examine this solution. This is what our app will look like:
Let’s first create a new SwiftUI watchOS project:
Select WatchOS and then Watch App:
Create Coloured List
Let’s navigate to ContentView.swift
and create ten colored circles in a vertical ScrollView
:
We marked colors
, an array of type Color, with @State
because we will need to modify it later on with the button that we are going to place beneath the navigation bar.
Then, in order to hide the button, we need to embed a structure called ScrollViewReader
(introduced with watchOS 7 and iOS 14) inside our ScrollView
:
The ScrollViewReader
structure provides a method called scrollTo()
that can move to any view inside the parent ScrollView
just by providing its anchor. This way, we can set the scrollTo()
value to the first element of our list (scrollTo(0)
) inside the onAppear
method, which is executed when the view appears.
We also introduced a new @State changed
to edit the colors
array only when needed.
The last step to finish our app is to create a Button
and place it before the ForEach
loop.
If we run our app now, the “Change Color” button should be hidden and we should be able to show it when dragging:
Thanks for reading! I hope you enjoyed this little tutorial and you learned something new. You can find the finished project on GitHub.