article

Monday, August 9, 2021

SwiftUI Simple Custom View Modifier

SwiftUI Simple Custom View Modifier
SwiftUI Views can be changed by using modifiers. To apply the same style to a particular view a custom view modifier can be used.
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        
        NavigationView {
             VStack {
                HStack {
                    Button("One") {
                        
                    }
                    .modifier(CustomButton())
                    
                    Button("Two") {

                    }
                    .modifier(CustomButton(buttonForegroundColor: Color.red))
                    
                    Button("Three") {
                        
                    }
                    .modifier(CustomButton(buttonForegroundColor: Color.yellow))
                    
                }
                Spacer()
            }
            .navigationTitle("Custom View Modifiers")
        }
    }
}

struct CustomButton: ViewModifier {
    var buttonForegroundColor = Color.blue
    
    func body(content: Content) -> some View {
        return content
            .font(.largeTitle)
            .background(Color.black)
            .foregroundColor(buttonForegroundColor)
            .cornerRadius(8.0)
            .padding(.top, 50.0)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Post