Search code examples
swiftswiftuiparameterssyntax

Is there a way to pass functions into views as optional parameters?


I am making an application in SwiftUI that involves answering yes or no questions. Because of this I have created a subview call YesOrNoView. This subview has two buttons, one labeled yes and the other labeled no. The view accepts a binding variable of question that returns true or false based on the users answer. It also accepts a binding variable of questionsAnswered and increments it whenever either button is pressed. This behavior works for most questions in the game, but for the final question I want it to execute custom logic to take the user to a different view. To do this I am trying to make the view accept a custom action/method that I can call from either buttons action logic. Ideally, the action would also be optional so that I don't have to pass it in the 99% percent of the time when I'm not using it.

How do I pass a function as an optional parameter into a view and then run that action when a button within said view is pressed?

I tried adding actions using

struct YesOrNoView<Content: Action>: View {

... but it couldn't find action or Action within it's scope.

I also tried using

struct YesOrNoView<Content>: View {

But I got an error saying that the Content variables type could not be inferred.

Any help would be greatly appreciated.


Solution

  • It return clickAction back to the view

     struct GenericButton<Title: StringProtocol>: View {
    
        let title: Title
        let action: () -> Void
    
        var body: some View {
            Button(action: action) {
                    Text(title)
                }.frame(width: 200, height: 40)
            }
        }
    }
    

    Usage:

    GenericButton("Button") {
    // Button tapped action
    }