SwiftUI: Reusable Components/Higher-Order-Components
How to use and manipulate HOC’s
**It seems Safari isn’t able to show code snippets, please try using Chrome**
If you’ve ever worked with React or React-Native, Higher-Order-Components are the design pattern of choice when reusing component behavior and UI.
This pattern isn’t foreign to iOS either. Check out this article on creating custom components on iOS.
SwiftUI’s HOC Syntax — The Right Way
Let's keep it really simple now. This is all the code that we need in order to create a Higher-Order-Component in SwiftUI:
Note: In the initializer, I purposely set
_ childView to conform to a closure type that returns our generic
View, this makes the code more readable. Alternatively, you can set it as this…
_ childView: C and call
ContainerViewdeclares a generic constraint for our
View, a.k.a Type Constraint Syntax
- We store the generic type as a property named
bodywe return the
- Simple! HOC successfully created!
Let’s get serious, we can’t truly appreciate HOC without a good practical example, let's dig in!
Creating a draggable HOC
What if we try to create a component that would give every child the ability to become draggable and spring back to their original position when released.
First, we need to create a new View component that we will name
DraggableView that adopts the HOC Syntax we wrote earlier.
Second, we have to write the business logic for the drag gesture and spring animation.
We can put
DraggableView into action by passing in the child components for rendering!
Voila! Just like that, we are done! I wasn't able to find any articles on creating HOC’s for SwiftUI, but I hope you enjoyed reading this article as much as I enjoyed writing it!
I’d also recommend checking this article on creating your own custom view modifiers, just like their name they modify your View.
Let me know your thoughts!