ios – How do I provide function as a parameter of struct


I’m learning SwiftUI. So I am creating weather app with @state toggling. I created button view but I’m struggling with passing isDark.toggle function as a parameter for my button view. I get Escaping autoclosure captures 'inout' parameter 'self'

I’ve my button view

struct WeatherButton: View {
    var text: String
    var action: () -> Void
    
    init(text: String, action: @escaping () -> Void) {
        self.text = text
        self.action = action
    }
    
    var body: some View {
        Button(action: {
            action()
        }, label: {
            Text(text)
                .frame(width: 280, height: 50)
                .background(.white)
                .font(.system(size: 20, weight: .bold))
                .cornerRadius(10)
        })
    }
}

and how i use it

@State private var isDark = false

...

WeatherButton(text: "Theme toggle doesn't work",
                              action: isDark.toggle)

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img