Make Your Own SwiftUI Modifier

Andrew Ho
1 min readJan 8, 2021

I Learn faster by Example

SwiftUI comes with a set of built-in view modifiers, for example. “.padding()”, that can be added toe Image, Text etc to request more space between views. Once we start to use these modifiers, they stack up and become cumbersome: It is inconvenient to copy-paste a large collection of them to reproduce the same look for similar elements in different part of the code.

This is where making our own custom view modifier becomes useful. For example:

Text(“+”)

.padding(EdgeInsets(top:2,leading:4,bottom:2,trailing:4))

.foregroundColor(.blue)

.overlay(RoundedRectangle(cornerRadius: 20).stroke(.blue, lineWidth: 1))

Becomes →

Text(“+”)

.myCustomStyle()

Here is how:

extension View {

public func myCustomStyle() -> some View {

return padding(EdgeInsets(top:2,leading:4,bottom:2,trailing:4))

.foregroundColor(.blue)

.overlay(RoundedRectangle(cornerRadius: 20).stroke(.blue, lineWidth: 1))

} // end view

} // end extension

  1. The public function can be further customized by passing in parameters.
  2. multiple public functions can reside in an “extension View” library. This makes it easier to customize the appearance of the app all in one place. Consequently removing the many / most of the styling info from the logic of the code into a separate file — functions as a “style sheet” library.

--

--