How To Configure Views In SwiftUI

Introduction

 
SwiftUI provides views, controls, and layout structures for declaring your app's user interface. The framework provides event handlers for delivering taps, gestures, and other types of input to your app, and tools to manage the flow of data from your app's models down to the views and controls that users will see and interact with.
 
Create your own custom views that conform to the View protocol, and compose them with SwiftUI views for displaying text, images, and custom shapes using stacks, list and more. Apply powerful modifiers to built-in views and your own views to customize their rendering and interactivity. Share code between apps on multiple platforms with views and controls that adapt to their context and presentation.
 
There are three different ways to configure a SwiftUI view,
  1. Initializers
  2. Modifiers
  3. inheritance 
When passing arguments to its initializer, using modifiers, and through its surrounding environment.
 
Example
 
In the below example we are configuring Text view that acts as the body of a TitleView 
  1. struct TitleView: View {  
  2.     var title: String  
  3.     var body: some View {  
  4.         Text(title)  
  5.             .font(.headline)  
  6.             .italic()  
  7.             .foregroundColor(.blue)  
  8.     }  
  9. }  
The above is an example of direct configuration, as we're explicitly setting up and modifying our Text view by directly calling methods on it. However, SwiftUI also supports indirect configuration.
 
The indirect configuration can be useful when we want multiple sibling views to adopt the same configuration or styling in the following example in which we configure both a Text and a List to display all of their text using a font, simply by assigning that font to their parent VStack.
 
Example
  1. struct ListView: View {  
  2.     var title: String  
  3.     var items: [Item]  
  4.     @Binding var selectedItem: Item?  
  5.   
  6.     var body: some View {  
  7.         VStack {  
  8.             Text(title).bold()  
  9.             List(items, selection: $selectedItem) { item in  
  10.                 Text(item.title)  
  11.             }  
  12.         }.font(.system(.body, design: .monospaced))  
  13.     }  
  14. }  
The above shows that the entire SwiftUI view hierarchies that can be configured through their parent are powerful. In SwiftUI views, you can share styles and configurations without having to modify each view separately. Not only does that often lead to less code, but it also establishes a single source of truth for our shred configuration - like fonts, colors -- without requiring us to. 
 
Let's take another example, in which we change an entire navigation stack's accentColor simply by assigning it to our root NavigationView which will be applied to all child views.
  1. struct ItemListView: View {  
  2.     @ObservedObject var items: itemList  
  3.     var body: some View {  
  4.         NavigationView {  
  5.             List(items) { item in  
  6.                 Text(item.itemName)
  7.             }  
  8.             .navigationBarItems(  
  9.                 trailing: Button(  
  10.                     action: { ... },  
  11.                     label: {  
  12.                         // This image will be colored purple  
  13.                         Image(systemName: "person.badge.plus")  
  14.                     }  
  15.                 )  
  16.             )  
  17.         }.accentColor(.purple)  
  18.     }  
  19. }  
However, sometimes we might want to apply a set of styles to a group of views without having to change their relationship to a parent view. 
 
For example, let's say that we're building a view for displaying an address within an app, which consists of a series of stacked Text Views :
  1. struct AddressView: View {  
  2.     var address: Address  
  3.     var body: some View {  
  4.         VStack(alignment: .leading) {  
  5.             Text(address.recipient)  
  6.                 .font(.headline)  
  7.                 .padding(3)  
  8.                 .background(Color.secondary)  
  9.             Text(address.street)  
  10.                 .font(.headline)  
  11.                 .padding(3)  
  12.                 .background(Color.secondary)  
  13.             HStack {  
  14.                 Text(address.postCode)  
  15.                 Text(address.city)  
  16.             }  
  17.             Text(address.country)  
  18.         }  
  19.     }  
  20. }  
Also, SwiftUI ships a Group type, which lets us treat a set of views as a group without affecting their layout, drawing or position within our overall view hierarchy. Using that type, we can group our two labels together and then apply our set of modifiers to both of them at the same time.
  1. struct AddressView: View {  
  2.     var address: Address  
  3.     var body: some View {  
  4.         VStack(alignment: .leading) {  
  5.             Group {  
  6.                 Text(address.recipient)  
  7.                 Text(address.street)  
  8.             }  
  9.             .font(.headline)  
  10.             .padding(3)  
  11.             .background(Color.secondary)  
  12.             ...  
  13.         }  
  14.     }  
  15. }  
The power of Group is that it applies its modifiers directly to its children, rather that to itself. Compare that to if we would have grouped our labels using another VStack instead, which would have caused the padding and background color to be applied to that stack, rather than to our labels indivisually.
 

Views versus extensions

 
As our SwiftUI- based views grow in complexity we likely need to start using multiple ways of growing and sharing our various configurations and styles, in order to keep our code easy to work with. So far, we have mostly been dealing with styling through modifiers, but a major part of our UI configuration also comes down to how we structure our views themselves.
 
Let's take an example on a form that lets a user sign up for an account within an app.
  1. struct SignUpForm: View {   
  2.     @State private var username = ""  
  3.     @State private var email = ""  
  4.     var body: some View {  
  5.         Form {  
  6.             Text("Sign up").font(.headline)  
  7.             HStack {  
  8.                 Image(systemName: "person.circle.fill")  
  9.                 TextField("Username", text: $username)  
  10.             }  
  11.             HStack {  
  12.                 Image(systemName: "envelope.circle.fill")  
  13.                 TextField("Email", text: $email)  
  14.             }  
  15.             Button(  
  16.                 action: { ... },  
  17.                 label: { Text("Continue") }  
  18.             )  
  19.         }  
  20.     }  
  21. }  
In the above example, we are using the same HStack+image +TextField combination twice, and that isn't necessarily a problem given that we're configuring each of our two text fields quite differently. Let's say we wanted to turn that combination into a stand-alone component that we could reuse in other places throughout our app.
 
Let's take an example that creates a new view type which takes an iconName and title to display, as well as a @Binding reference to the text property that we wish to update whenever our component's text field was edited. 
  1. struct IconPrefixedTextField: View {  
  2.     var iconName: String  
  3.     var title: String  
  4.     @Binding var text: String  
  5.     var body: some View {  
  6.         HStack {  
  7.             Image(systemName: iconName)  
  8.             TextField(title, text: $text)  
  9.         }  
  10.     }  
  11. }  
We can now use the above example on SignUpForm and replace our previously duplicated HStack configurations with instances of our new IconPrefixedTextField component 
  1. struct SignUpForm: View {  
  2.     var body: some View {  
  3.         Form {  
  4.             IconPrefixedTextField(  
  5.                 iconName: "person.circle.fill",  
  6.                 title: "Username",  
  7.                 text: $username  
  8.             )  
  9.             IconPrefixedTextField(  
  10.                 iconName: "envelope.circle.fill",  
  11.                 title: "Email",  
  12.                 text: $email  
  13.             )  
  14.         }  
  15.     }  
  16. }  
The above example change will enable us to reuse our new IconPrefixedField type outside of SignUpForm.
 

Conclusion

 
SwiftUI offers a number of ways for us to structure our UI code and the way we configure our various views. While many of our custom components are likely going to be implemented as stand-alone View types, building our own extension and modifiers can enable us to share styles and configurations across a codebase in a much more lightweight manner.