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

时间:2020-04-28 12:47:46

标签: 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()
        }
    }
}

但是当我尝试使用它时...

struct MyView : View {
    var body : some View {
        MyCustomButton(action: { doSomething() }) {
            Text("My custom button")
        }
    }
}

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

2 个答案:

答案 0 :(得分:2)

已经弄清楚了:

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

答案 1 :(得分:0)

您不需要更改Button,根据SwiftUI的设计意图,只需提供自定义ButtonStyle,就像下面的示例一样。

struct ScaleButtonStyle: ButtonStyle {
    let bgColor: Color
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .background(bgColor)
            .scaleEffect(configuration.isPressed ? 5 : 1)
    }
}

struct DemoScaleButtonStyle: View {
    var body: some View {
        Button(action: { }) {
            Text("Button")
                .foregroundColor(.white)
        }.buttonStyle(ScaleButtonStyle(bgColor: Color.red))
    }
}