SwiftUI - 在视图中包装 Button,以创建自定义按钮

Phi*_*den 3 button swiftui

我正在尝试创建我自己的 Button 版本,方法是将其包装在视图中,从而打开添加更多功能/隐藏样式修饰符的能力。我知道这不会带来好处,而且 ButtonStyles 很强大。但是为了超级干净的代码,我很好奇它是如何实现的。

在最精简的形式中,我想写一些类似的东西(基于 Button 自己的签名):

struct MyCustomButton: View {
    let action : () -> Void
    let contents : () -> PrimitiveButtonStyleConfiguration.Label

    var body : some View {
        Button(action: self.action) {
            self.contents()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,当我尝试使用它时......

struct MyView : View {
    var body : some View {
        MyCustomButton(action: { doSomething() }) {
            Text("My custom button")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

...我收到以下编译错误:无法将“文本”类型的值转换为关闭结果类型“PrimitiveButtonStyleConfiguration.Label”

Phi*_*den 7

已经想通了:

struct NewButton<Content: View> : View {
    let content : ()-> Content
    let action: () -> Void

    init(@ViewBuilder content: @escaping () -> Content, action: @escaping () -> Void) {
        self.content = content
        self.action = action
    }

    var body: some View {
        Button(action: self.action) {
            content()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)