SwiftUI streamlines many of the common functionalities, capabilities, and controls common in apps. It is quite apparent that a focus during development was to consider how devs could incorporate common UI elements simply and with a lot of the overhead powerfully automated. The framework even takes into consideration usability and design perspectives.

This is extremely welcomed by the iOS community, which has had experience working with Interface Builder, Storyboards, and ViewControllers. Anyone who has dealt with the complexity that even the most simplistic features demanded could understand SwiftUI’s benefits.


The Catch?

As devs begin to build out more and more complex apps with SwiftUI, there are times when it feels like features (such as Navigation) are almost _too_simplistic. As I scroll through Stack Overflow Q&A’s, I see an increasing number of tagged issues that ask for more dev control. Likewise, I see a number of solutions that involve wrapping older UIKit solutions to cover the gaps.

My hope is that as SwiftUI continues to mature and develop, we will see less and less UIKit and more SwiftUI (and that definitely seemed to be the case at this year’s WWDC20).

But it’s also my hope that we only resort to tapping into another framework as a last resort. Perhaps we can find pure SwiftUI solutions, as Apple suggests, though they may seem hacky and/or less pretty. I’d argue, though, that we’d be doing the same by pulling in UIKit.

For the record: I have nothing truly against UIKit — just a healthy desire to reduce dependency and see a new framework stand on its own.


SwiftUI Unwind?

One such ability that devs seem to miss is having an unwind. We get a back button for “free” with Navigation, but there’s no option to add any code or completions to it. Way back in the olden UIKit days, there were a few options. If we had been using a segue, we could put code into an unwind. The other option was using viewWillDisapear or some other lifecycle event.

With SwiftUI, in the instance that a developer wants to run some code before navigating back to the parent (and not immediately on a binding change), the best we can naturally do “for free” is trigger .onDisappear(listed as one of SwiftUI’s lifecycle events). However, this is technically running as the parent is already coming into view, which may produce awkward UI results. And since the parent in a NavigationView is already appearing, onAppear is not a safe bet.

The other approach, then, is to take matters into our own hands and create a custom back button. This is natural because, although we’re not using the button created for free, we are given the ability to add bar items to our view. Should our app call for more than simply navigating back, we should absolutely take advantage of this approach.

#swift #mobile #ios #programming #swiftui

The Case for Using Custom Back Buttons in SwiftUI
1.30 GEEK