[英]SwiftUI pass Swift code as a parameter for reusable views
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, eg:但是,我还想指定由于单击可重用按钮而应运行的代码,例如:
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.然后,这将 go 到自定义视图上,所述按钮应该 go 在用户使用可重用按钮视图主体内的导航视图单击时。
How would I get around this?我将如何解决这个问题? I tried the state:
我试过 state:
@State var action = -> Void
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!注意:不要将
@State
包装器用于公共视图属性!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.