admaDIC App Development & IT Solutions

SwiftUI ViewModifier

by Annett Schwarze | 2025-10-30

SwiftUI provides so called ViewModifiers. A ViewModifier is a reusable type that defines how to change or decorate a view's appearance or behavior.

In the sample code two custom ViewModifiers Heading1 and Subheading1 are used to style text elements. The modifiers make it easy to apply consistent styles to multiple view elements.

        
import SwiftUI

struct SampleViewModifier2View: View {
    var body: some View {
        VStack(spacing: 16, content: {
            Text("ViewModifier")
                .font(Font.largeTitle)

            VStack {
                Text("Heading")
                    .modifier(Heading1())
                Text("Subheading")
                    .modifier(Subheading1())
                Text("Subheading")
                    .modifier(Subheading1())
                Text("Heading")
                    .modifier(Heading1())
                Text("Subheading")
                    .modifier(Subheading1())
                Spacer()
            }
        })
    }

    struct Heading1: ViewModifier {
        func body(content: Content) -> some View {
            content
                .font(.largeTitle)
                .foregroundColor(.green)
                .frame(maxWidth: .infinity)
                .padding(8)
                .background(Color.green.opacity(0.1))
                .clipShape(Capsule())
                .overlay {
                    Capsule().stroke(Color.green, lineWidth: 1)
                }
                .padding(.horizontal, 12)
        }
    }

    struct Subheading1: ViewModifier {
        func body(content: Content) -> some View {
            content
                .font(.title2)
                .foregroundColor(.blue)
                .frame(maxWidth: .infinity)
                .padding(4)
                .background(Color.blue.opacity(0.1))
                .clipShape(Capsule())
                .overlay {
                    Capsule().stroke(Color.blue, lineWidth: 1)
                }
                .padding(.horizontal, 24)
        }
    }
}

#Preview {
    SampleViewModifier2View()
}
    
SwiftUI ViewModifier

 

www.admadic.de | webmaster@admadic.de | Legal Notice and Trademarks | Privacy
© 2005-2007 - admaDIC | All Rights Reserved
All other trademarks and/or registered trademarks are the property of their respective owners
Last Change: Thu Oct 30 08:33:08 2025 GMT