针对 Xcode 13.0 beta 2 更新
SwiftUI
有许多造型协议,使我们能够确定共同的造型为观点如Button
,ProgressView
,Toggle
,等。它们都通过允许我们集中任意数量的修饰符来工作,这些修饰符使视图看起来像我们想要的那样,并提供修饰符让我们在一行中应用全套自定义。
例如,这里有一个按钮,其样式声明为内联:
Button("Press Me") {
print("Button pressed!")
}
.padding()
.background(Color(red: 0, green: 0, blue: 0.5))
.clipShape(Capsule())
这适用于单个按钮,但如果这是整个应用程序的标准按钮设计,您应该考虑使用自定义按钮样式。这意味着创建一个符合ButtonStyle
协议的新结构,它将向我们传递按钮的配置以按照我们想要的方式执行操作。
因此,我们可以将这三个修饰符集中到一个BlueButton
样式中,然后将其应用到我们的按钮上,如下所示:
struct BlueButton: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.background(Color(red: 0, green: 0, blue: 0.5))
.foregroundColor(.white)
.clipShape(Capsule())
}
}
struct ContentView: View {
var body: some View {
Button("Press Me") {
print("Button pressed!")
}
.buttonStyle(BlueButton())
}
}
取消Button
点击高亮效果,根据自己的序幕需求自行设置
extension Color {
static let defaultBlue = Color(red: 6, green: 44 / 255.0, blue: 255 / 255.0)
static let paleBlue = Color(red: 194 / 255.0, green: 224 / 255.0, blue: 253 / 255.0)
static let paleWhite = Color(white: 1, opacity: 179 / 255.0)
}
struct MyButtonStyle: ButtonStyle {
@Environment(\.isEnabled) var isEnabled
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
// change the text color based on if it's disabled
.foregroundColor(isEnabled ? .white : .paleWhite)
.background(RoundedRectangle(cornerRadius: 5)
// // change the background color based on if it's disabled
.fill(isEnabled ? Color.defaultBlue : Color.paleBlue)
)
// make the button a bit more translucent when pressed
.opacity(configuration.isPressed ? 0.98 : 1.0)
// make the button a bit smaller when pressed
.scaleEffect(configuration.isPressed ? 0.98 : 1.0)
}
}
网友评论