Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI – Is it possible to add function prompt in custom tool bar viewModifier

I have created following custom toolbar modifier which I use in number of app screens . The only change on each screen is the function which added to the button! How can I add a function prompt inside the custom toolbar modifier so I can update function for each screen?

Thank You!

Following is the code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import Foundation
import SwiftUI

struct toolbarModifier: ViewModifier {
func body (content: Content) -> some View {
    content
    .toolbar {
        ToolbarItem (placement: .navigationBarTrailing) {
            Button {
                // addItem() function for example
            } label: {
               Image (systemName: "checkmark.circle.fill")
            }
        }
    }
}

}

I tried searching on the website but couldn’t find any answer!

>Solution :

You can pass it as a variable

struct ToolbarModifier: ViewModifier { //struct should start with uppercase
    //This is how you declare a function
    let action: () -> Void
    func body (content: Content) -> some View {
        content
            .toolbar {
                ToolbarItem (placement: .navigationBarTrailing) {
                    Button(action: action) { //Use it in the action of the Button
                        Image (systemName: "checkmark.circle.fill")
                        
                    }
                }
            }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading