onChange(of:perform:)
是 SwiftUI 用于监测某个参数变化的方法,可以在参数变化时执行代码块。该方法有两个参数:
of
:要监测的参数,一般是绑定的对象,比如@State
、@Binding
等;perform
:当参数变化时要执行的代码块。
代码演示如下:
struct ContentView: View {
@State var count = 0
var body: some View {
VStack {
Text("\(count)")
Button("Count up") {
count += 1
}
}
.onChange(of: count) { newValue in
print("Count changed to \(newValue)")
}
}
}
在上面的例子中,我们监测了 count
参数的变化,并在变化时打印输出新值。当我们点击按钮增加计数时,控制台会输出:
Count changed to 1
Count changed to 2
Count changed to 3
...
可以看到,每次 count
的值变化时,都会执行 perform
中的代码块。