ios - 如何在 SwiftUI 中提供自定义 ButtonStyle 附加选项
问题描述
我目前有一个 ButtonStyle 定义如下:
struct RoundedButtonRed: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
HStack {
Spacer()
configuration.label.foregroundColor(.white)
Spacer()
}
.padding()
.background(Color.red.cornerRadius(13.0))
.scaleEffect(configuration.isPressed ? 0.85 : 1)
}
}
我还有另一个 struct ( RoundedButtonBlack
) 有一个.background(Color.black.cornerRadius(13.0))
,这似乎是不必要的代码重复。有没有办法添加自定义配置选项,以便我可以将相同的结构用于不同的颜色?
例如
struct RoundedButtonRed: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
HStack {
Spacer()
configuration.label.foregroundColor(.white)
Spacer()
}
.padding()
.background(configuration.backgroundColor) // background color taken from configuration or passed into .buttonStyle(RoundedButton()) call
.scaleEffect(configuration.isPressed ? 0.85 : 1)
}
}
或者,也许有更好的方法?
解决方案
只需在RoundedButton
存储颜色的结构中添加一个属性。然后,当你用 应用它时buttonStyle
,你可以传入任何你想要的颜色。
struct RoundedButton: ButtonStyle {
var color: Color /// add property here
func makeBody(configuration: Configuration) -> some View {
HStack {
Spacer()
configuration.label.foregroundColor(.white)
Spacer()
}
.padding() /// use it here
.background(color.cornerRadius(13.0))
.scaleEffect(configuration.isPressed ? 0.85 : 1)
}
}
struct ContentView: View {
var body: some View {
VStack { /// pass it in here
Button("Red button") {}.buttonStyle(RoundedButton(color: .red))
Button("Black button") {}.buttonStyle(RoundedButton(color: .black))
}
}
}
结果:
推荐阅读
- angular - Angular 4 验证器在部署到服务器时工作方式不同
- visual-studio - 具有相同依赖项的 Visual Studio 解决方案中的多个项目会产生不同的 pdb 大小
- google-chrome-extension - 你可以在 iframe 中添加一个 chrome 扩展,如果可以的话,怎么做?
- pytorch - Pytorch - 如何有效地形成这个变换张量?
- wicket - 检票口下拉选项在验证错误时重置为“选择一个”
- docker - 如何访问远程 Droplet 服务器上的 Jenkins 仪表板?
- c - 有间隙的随机数
- r - R中的最小绝对偏差
- apache-pig - 用 NULL 替换 PIG
- python-3.x - 使用 python 为网站创建仪表板