Build SwiftUI User Interface By Using Composable Styling in SwiftUI

No more repeating user interface controls and components

Tatenda Kabike
2 min readJul 27, 2021

It is quite common that in every SwiftUI application we use many controls, components and views.If the project is large you tend to continuously repeat and implement these controls in every screen. However in SwiftUI provides the ability to create styles for your controls and views, in this article we are going to demonstrate using two common controls , Button and TextField. But you can also apply styles on various UI components like Pickers, Views, Shapes and so on.

The code below shows a simple user interface with a Button and a TextField.

Let create a style for TextField

The code above creates a simple style that can be applied to TextField controls. The most important part of the code above is the TextFieldStyle protocol this is gives the ability to modify appearance and to add functional custom code to your style.

Button Style:

The code above creates a simple button style that applies a blue border and corner radius.

Applying Styles

They are many different ways to apply custom styles to controls.

  1. You can apply the style directly to your components
  2. You can apply it globally via the Scene Delegate
  3. You can apply to the parent only.

Modifying our initial code with the code below:

The Button and TextField controls appearance is changed accordingly.

Let try to apply these styles via the parent add the code below:

The code above applies styles through the parent in this case the VStack is our parent. If you add the styles to the parent it will affect every Button and TextField child contained within. I think by now you can appreciate how styles can make your UI code clean and readable.

And finally you can apply your styles globally in your app where your styles is applied through out the application. To archive this we will declare your styles via the SceneDelegate, inside the scene function.

Modify your SceneDelegate file as above and remove the styles you applied in the ContentView view and run your application you will see the styles applied to the Button and TextField respectively.

Finally you can also apply the styles globally using the Environment i will add another tutorial on how to apply styles via Environment. I hope you enjoyed this article.

--

--

Tatenda Kabike

IOS mobile developer, content creator, i love experimenting with ARKit & CoreML. I love travelling and nature when i am off the machine.