在我的应用程序中,我有一个按钮,每次按下都会输出一个特定的警报。但是,我希望这样,当我单击该按钮10次时,该按钮的操作和标签将发生变化,因为我希望将其转换为重新启动按钮。我怎样做呢?
换句话说,当按钮没有名称时,我如何引用它并修改它的属性?
“”斯威夫特
Button(action: { alertIsVisible = true
}) {
Text(buttonText)
.fontWeight(.bold)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(20)
}
.alert(isPresented: $alertIsVisible, content: {
let roundedValue = Int(sliderValue.rounded())
let points = game.points(sliderValue: roundedValue)
return Alert(title: Text("Hello!"), message: Text("The slider's value is \(roundedValue).\n" + "You scored \(points) points this round"), dismissButton: .cancel(
{game.target = Int.random(in: 1...100)
roundTracker += 1
scoreTracker += points
}
))
})
“”“
发布于 2021-08-26 06:21:19
下面是一个示例,其中计数器被存储为一个@State
。当counter
到达10
时,它会显示“重新启动”按钮。
struct ContentView: View {
@State private var counter = 0
var body: some View {
if counter < 10 {
Button("Press") {
print("button pressed: \(counter)")
counter += 1
}
} else {
Button("Restart") {
print("restart...")
counter = 0
}
}
}
}
结果:
发布于 2021-08-26 06:43:51
您可以根据一个label
变量的值来更改Button
的Button
和counter
(如果它是用属性包装器@State
很好地声明的)
我在这里用了三元操作符:
struct CounterView: View {
@State private var counter: Int = 0
var exceeded: Bool { counter >= 10 }
func restart() {
// do something
counter = 0
}
func increment() {
counter += 1
}
var body: some View {
Button(exceeded ? "Restart" : "Increment", action: exceeded ? restart : increment)
}
}
编辑:
当然,您可以使用经典的if/else
,而不是三元操作符。但它将破坏 any 动画,如本例所示(使用if / else,这是两个不同的按钮,动画由一个经典转换代替,默认情况下淡入/淡出):
struct CounterView: View {
@State private var counter: Int = 0
var exceeded: Bool { counter >= 1 }
func restart() {
withAnimation(.linear(duration: 2)) {
counter = 0
}
}
func increment() {
counter += 1
}
var body: some View {
VStack {
Button(exceeded ? "Restart" : "Increment", action: exceeded ? restart : increment)
.foregroundColor(.red)
.scaleEffect(exceeded ? 2 : 1)
if exceeded {
Button("Restart", action: restart)
.scaleEffect(exceeded ? 2 : 1)
} else {
Button("Increment", action: increment)
.scaleEffect(exceeded ? 2 : 1)
}
}
}
}
https://stackoverflow.com/questions/68940168
复制相似问题