Reputation: 1762
I'm organising my code and I have this custom Button view that I have made:
@State var buttonName = ""
@State var imageName = ""
Button(action: {
// Code that should be passed as a parameter to be run
}){
HStack(spacing: 15){
Image(systemName: imageName).resizable().frame(width:40, height: 40)
Text(buttonName)
Spacer(minLength: 15)
Image(systemName: "chevron.right")
}.padding()
.foregroundColor(Color.black.opacity(0.5))
}
With this setup I can reuse this view as such:
buttonView(buttonName: "Logout", imageName: "person.fill")
However I'd like to also specify code that should be run as a result of clicking the reusable button, e.g.:
buttonView(buttonName: "Logout", imageName: "person.fill", action: {Logout()})
This would then go onto custom views said buttons should go to upon the user clicking using a Navigation View within the reusable button view's body.
How would I get around this? I tried the state:
@State var action = -> Void
Upvotes: 2
Views: 371
Reputation: 257563
Here is a demo view for that purpose
struct DemoView: View {
let action: () -> ()
var body: some View {
Button("Demo", action: action)
}
}
Note: don't use @State
wrapper for public view properties!
Upvotes: 2