[英]SwiftUI - reusable components with links to other views as parameters
[英]SwiftUI pass Swift code as a parameter for reusable views
我正在組織我的代碼,並且我已經制作了這個自定義按鈕視圖:
@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))
}
通過這個設置,我可以像這樣重用這個視圖:
buttonView(buttonName: "Logout", imageName: "person.fill")
但是,我還想指定由於單擊可重用按鈕而應運行的代碼,例如:
buttonView(buttonName: "Logout", imageName: "person.fill", action: {Logout()})
然后,這將 go 到自定義視圖上,所述按鈕應該 go 在用戶使用可重用按鈕視圖主體內的導航視圖單擊時。
我將如何解決這個問題? 我試過 state:
@State var action = -> Void
這是用於此目的的演示視圖
struct DemoView: View {
let action: () -> ()
var body: some View {
Button("Demo", action: action)
}
}
注意:不要將@State
包裝器用於公共視圖屬性!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.