是否可以使用SwiftUI在动作关闭中获得按钮本身?
struct ContentView: View {
var body: some View {
Button("test") {
// change the color of button when user is tapping on it
}
}
}
答案 0 :(得分:0)
方法如下:
struct ContentView: View {
@State var color = Color.red
var body: some View {
Button("test") {
self.color = Color.green
}.background(color)
}
}
答案 1 :(得分:0)
如果要访问按钮的属性,则可以创建自定义ButtonStyle
。
使用其configuration
设置所需的行为。
struct CustomButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
.foregroundColor(.white)
.background(LinearGradient(gradient: Gradient(colors: [.red, .orange]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
.scaleEffect(configuration.isPressed ? 0.9 : 1)
}
}
以上示例摘自此处:SwiftUI Tip: ButtonStyle and Animated Buttons
根据您的情况,可以对其进行调整以设置自定义背景:
.background(configuration.isPressed ? Color.red : Color.blue)
答案 2 :(得分:0)
是的...我也自己弄清楚
struct ContentView: View {
@State var buttonColor: Color = Color.clear
var body: some View {
Button(action: {
self.buttonColor = Color(red: Double.random(in: 0...1),
green: Double.random(in: 0...1),
blue: Double.random(in: 0...1))
}, label: {
Text("Button").background(buttonColor)
})
}
}