【问题标题】:Why does my Button style object only work on the text within the button and not the entire button?为什么我的 Button 样式对象仅适用于按钮内的文本,而不适用于整个按钮?
【发布时间】:2020-04-24 19:35:48
【问题描述】:

我有一个ButtonStyle 对象,我希望在点击Button 时使用它。但是,当我在我的Button 上调用它时,效果仅在按钮内的文本上可见,而不是在整个Button 上。 我试过在外面打电话,但无济于事。有人可以向我解释如何解决我的错误吗?

Button(action: {

    }) {
        Text("Button")
            .foregroundColor(.white)
    }.background(Color.red)
     .buttonStyle(ScaleButtonStyle())


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

编辑:

Button(action: {}) {
            Text("Button")
                .fontWeight(.semibold)
                .foregroundColor(.white)
                .font(.title)
        }
        .buttonStyle(ScaleButtonStyle(bgColor: Color.red))
        .frame(width: geo.size.width*0.8, height: geo.size.height*0.1, alignment: .center)
        .background(Color.red)
        .clipShape(Rectangle())


struct ScaleButtonStyle: ButtonStyle {
 let bgColor: Color

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

【问题讨论】:

    标签: button swiftui


    【解决方案1】:

    解决方案是将背景作为按钮样式的一部分,如下所示。

    使用 Xcode 11.4 / iOS 13.4 测试

    struct ScaleButtonStyle: ButtonStyle {
        let bgColor: Color
        func makeBody(configuration: Self.Configuration) -> some View {
            configuration.label
                .background(bgColor)
                .scaleEffect(configuration.isPressed ? 5 : 1)
        }
    }
    
    struct TestScaleButtonStyle: View {
        var body: some View {
            Button(action: { }) {
                Text("Button")
                    .foregroundColor(.white)
            }.buttonStyle(ScaleButtonStyle(bgColor: Color.red))
        }
    }
    

    【讨论】:

    • 非常感谢您的回复,但不幸的是,代码仍然只使按钮视图中的文本视图缩放,而不是按钮本身的整个框架。编辑:已编辑问题以使用您建议的 ButtonStyle 结构反映代码
    • @mogoco8594、scaleEffect 以及任何其他几何效果都不会更改视图的布局框架,因此任何此类修改只会影响按钮的呈现,而不影响布局。
    • 对不起,我没有意识到这一点,感谢您的解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多