【问题标题】:SwiftUI pass Swift code as a parameter for reusable viewsSwiftUI 将 Swift 代码作为参数传递给可重用视图
【发布时间】:2020-12-28 16:19:24
【问题描述】:

我正在整理我的代码,并且我已经制作了这个自定义按钮视图:

@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()})

然后,这将进入自定义视图,当用户使用可重用按钮视图主体中的导航视图单击时,按钮应该进入该自定义视图。

我将如何解决这个问题?我试了一下状态:

@State var action = -> Void

【问题讨论】:

    标签: ios swift macos swiftui


    【解决方案1】:

    这是一个演示视图

    struct DemoView: View {
        let action: () -> ()
    
        var body: some View {
            Button("Demo", action: action)
        }
    }
    

    注意:不要对公共视图属性使用 @State 包装器!

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 2019-12-19
      • 1970-01-01
      • 2011-06-27
      相关资源
      最近更新 更多