SwiftUI Custom Modifiers

Custom modifiers encapsulate multiple modifiers in a single structure, and we can apply them later to the views.

struct ImageModifier: ViewModifier {
func body(content: Content) -> some View {
content
.scaledToFill()
.shadow(color: .black, radius: 5, x: 5, y: 5)
.cornerRadius(10)
}
}

The struct must conform to the ViewModifier protocol and implement the method called body that receives a parameter of type Content. It concatenates a chain of modifiers to build a final view.

Let’s see how to implement this.

struct ImageEditor: View {
var body: some View {
Image("sampleios")
.resizable()
.modifier(ImageModifier())
}
}

In the above example we are making image content scaled to fill and corner radius as 10. we can also other modifiers. Now we can use this same modifier for multiple images.

We can also customise this so that our modifier takes an input which can change its modifier value.

struct ImageModifier: ViewModifier {
var cornerRadius: CGFloat
init(radius: CGFloat) {
cornerRadius = radius
}
func body(content: Content) -> some View {
content
.scaledToFill()
.shadow(color: .black, radius: 5, x: 5, y: 5)
.cornerRadius(cornerRadius)
}
}

Here corner radius can be set by the Image and it will be reflected.

Let see how to make this code cleaner. A better way is to add our custom modifier as an extension on Image

extension Image {
func imageModifier(cornerRadius: CGFloat = 10) -> some View {
modifier(MyModifier(radius: cornerRadius))
}
}

Now we can re-write out ImageEditor struct as:

struct ImageEditor: View {
var body: some View {
Image("sampleios")
.resizable()
.imageModifier(cornerRadius:50)
}
}

These custom Modifiers and its extension can be used with any UI component like Image,View ,Text etc.

Keep coding.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store