Button 视图可以用来显示一个交互式按钮元素。
我们可以这样来声明它。
Button("Button label") {
//this happens when it's tapped
}
或者用这种方式。
Button {
//this happens when it's tapped
} label: {
Text("Button label")
}
当你有其他东西作为按钮的标签,而不是文本时,第二种方式更常见。例如一张图片。
让我们在一个SwiftUI程序中使用第一种方式。
struct ContentView: View {
var body: some View {
Button("Test") {
}
.font(.title)
}
}
看到了吗?在程序中,有一个蓝色的文本,你可以点击它。它是互动的。

我们没有告诉它在点击时要做什么,所以它就做任何事情。
我们可以打印一些东西到调试控制台。
struct ContentView: View {
var body: some View {
Button("Test") {
print("test")
}
.font(.title)
}
}
注意,这只在你运行应用程序时起作用,而不是在Xcode预览中。
现在我们可以给我们的应用程序添加另一个步骤。我们将在按钮标签内打印一个属性值。
struct ContentView: View {
var count = 0
var body: some View {
Button("Count: \(count)") {
}
.font(.title)
}
}
当它被点击的时候,我们会增加计数。
struct ContentView: View {
var count = 0
var body: some View {
Button("Count: \(count)") {
self.count += 1
}
.font(.title)
}
}
但是应用程序将无法编译,出现错误
Left side of mutating operator isn't mutable: 'self' is immutable❌
我们需要在声明属性之前使用@State 属性包装器。
struct ContentView: View {
@State var count = 0
var body: some View {
Button("Count: \(count)") {
self.count += 1
}
.font(.title)
}
}
现在应用程序可以工作了,我们可以点击标签来增加count 的属性值。

当然,在我们下次运行时,计数器将从0开始,因为我们没有以任何方式持久化状态。我们稍后会讨论这个问题。