Custom Modifier SwiftUI

SwiftUI also allows you to create your own custom modifiers. This can be particularly useful if you have a standard set of modifiers that are frequently applied to views. Suppose that the following modifiers are a common requirement within your view declarations:

struct ContentView: View {
    var body: some View {
        
        Text("Hello Reader")
            .font(.largeTitle)
            .background(Color.white)
            .border(Color.gray, width: 0.2)
            .shadow(color: Color.black, radius: 5, x: 0, y: 5)
        
    }
}

Instead of applying these four modifiers each time text with this appearance is required, a better solution is to group them into a custom modifier and then reference that modifier each time the modification is needed. Custom modifiers are declared as structs that conform to the ViewModifier protocol and, in this instance, might be implemented as follows:

//
//  StandardTitle.swift
//  Custom Modifier
//
//  Created by JOYNAL ABEDIN on 14/9/22.
//

import SwiftUI

struct StandardTitle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.largeTitle)
            .background(Color.white)
            .border(Color.gray, width: 0.2)
            .shadow(color: Color.black, radius: 5, x: 0, y: 5)
    }
}

The custom modifier is then applied when needed by passing it through to the modifier() method:

//
//  ContentView.swift
//  Custom Modifier
//
//  Created by JOYNAL ABEDIN on 14/9/22.
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        
        Text("Hello Reader")
            .modifier(StandardTitle())
        
    }
}

With the custom modifier implemented, changes can be made to the StandardTitle implementation and those changes will automatically propagate through to all views that use the modifier. This avoids the need to manually change the modifiers on multiple views.

References: Neil Smyth

Github Repo: https://github.com/Joynal279/Custom-Modifier

20 thoughts on “Custom Modifier SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *