How to create custom reusable container views in SwiftUI
Learn how to build a generic custom container in SwiftUI.
12 Aug 2024 · 4 min read
When building iOS apps with SwiftUI, we sometimes need to create a custom reusable container view which can be used as any other SwiftUI container view with any kind of content.
In this article, we'll explore how to create such containers.
Let's dive in.

Understanding the basics of container views in SwiftUI
In SwiftUI, container views are components that encapsulate and manage the layout of their child views, arranging them in a certain way. Common examples include HStack, VStack or List.
When creating custom container views, SwiftUI provides methods to access contained child views, sections or container values which allow a high level of customization.
Creating a simple custom container
Let's start by creating a simple custom container view which adds some styling to the content view.
import SwiftUIstruct CustomContainer<Content: View>: View {@ViewBuilder var content: Contentvar body: some View {VStack {content}.padding().background(...).cornerRadius(10)}}
In this example, our container takes a closure returning a Content view. The @ViewBuilder attribute allows the closure to return multiple child views:
CustomContainer {Text(...)Image(...)...}
Adding custom styling to each subview
SwiftUI allows access to each subview passed into the container, enabling us to apply specific styling to each one. For example:
ForEach(subviewOf: content) { subview insubview.background(...)
Adding sections
Additionally, SwiftUI gives us access to each Section view and its content that was defined within the container:
ForEach(sectionOf: content) { section inVStack {Text(section.header)section.content.background(...)}}
Container values
To add more customization, we can use container values. Container values give us the possibility to configure specific child views. For example:
CustomContainer {Text(...).highlight(true)Image(...)...}
Within the container, we can access container values as follows:
ForEach(subviewOf: content) { subview insubview.background(subview.containerValues.isHighlighted ? .green : .grey)}
To dive deeper into container values, check out this article on understanding container values in SwiftUI (coming soon).



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



