首页 > 解决方案 > 单击另一个按钮时如何更改一个按钮的操作(SwiftUI)?

问题描述

在我的应用程序中,我有一个按钮,每次按下它都会输出一个特定的警报。但是,我想要它,以便当我单击该按钮 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
                                    }
                        ))
                    
                })

'''

标签: swiftbuttonswiftuireference

解决方案


这是一个示例,其中计数器存储为@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
            }
        }
    }
}

结果:

结果


推荐阅读