enum SectionType: String, CaseIterable {
case top = "Top"
case best = "Best"
}
struct ContentView : View {
@State private var selection: Int = 0
var body: some View {
SegmentedControl(selection: $selection) {
ForEach(SectionType.allCases.identified(by: \.self)) { type in
Text(type.rawValue).tag(type)
}
}
}
}
如何运行代码(例如print("Selection changed to \(selection)")
当。。。的时候$selection
状态变化?我浏览了文档,但找不到任何东西。
iOS 14.0+
您可以使用onChange(of:perform:) https://developer.apple.com/documentation/swiftui/view/onchange(of:perform:)修饰符,像这样:
struct ContentView: View {
@State private var isLightOn = false
var body: some View {
Toggle("Light", isOn: $isLightOn)
.onChange(of: isLightOn) { value in
if value {
print("Light is now on!")
} else {
print("Light is now off.")
}
}
}
}
iOS 13.0+
以下作为延伸Binding
,因此只要值发生变化就可以执行闭包。
extension Binding {
/// When the `Binding`'s `wrappedValue` changes, the given closure is executed.
/// - Parameter closure: Chunk of code to execute whenever the value changes.
/// - Returns: New `Binding`.
func onUpdate(_ closure: @escaping () -> Void) -> Binding<Value> {
Binding(get: {
wrappedValue
}, set: { newValue in
wrappedValue = newValue
closure()
})
}
}
像这样使用例如:
struct ContentView: View {
@State private var isLightOn = false
var body: some View {
Toggle("Light", isOn: $isLightOn.onUpdate(printInfo))
}
private func printInfo() {
if isLightOn {
print("Light is now on!")
} else {
print("Light is now off.")
}
}
}
This example doesn't need to use a separate function. You only need a closure.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)