SwiftUI: Custom Modal (Half Sheet)

Issue

Current SwiftUI offers .sheet() for modal presentation, but there is no control over the look and feel. Moreover there is no native half sheet (as is seen for example in safari) implementation. To our misfortune this design is quite popular between designers. So you have two options, convince your designer it’s not a good idea, or shut up and implement it.

Solution

This is the final result (screenshot from my UI kit). And how it can be used in the code.

Half sheet implemented in Swift UI

And here is how it’s used. First of all you have to create anchor point, from where the modal will be launched.

And then you can initialized from any of your views as is below:

Implementation

We are going to create Modal.swift (model), the AnchorView.swift, ModalManager.swift and ModalView.swift. Let’s start with the model. This implementation is inspired by cyrilzakka/SwiftUIModal.

Now let’s create the anchor view.

Now we can implement our ModalManager, that will handle when to show or hide our modal.

And finally the ModalView. This one seems little bit longer, but most of it’s implementation is in the method onDragEnded(), that is used for determining where to snap the sheet.

iOS Elements

You can find also the whole implementation in my UI kit — Download below.

Use discount code MOLCIK to get iOS Elements for $29.70 (70% off) 

References

Buy me a coffeeOut of coffee 😱, please help!