gpt4 book ai didi

ios - 如何在状态更改时运行操作?

转载 作者:可可西里 更新时间:2023-11-01 00:38:29 24 4
gpt4 key购买 nike

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)
}
}
}
}

$selection 状态发生变化时,如何运行代码(例如 print("Selection changed to\(selection)")?我查看了文档,然后我找不到任何东西。

最佳答案

iOS 14.0+

您可以使用 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.")
}
}
}

此示例不需要使用单独的函数。你只需要一个闭包。

关于ios - 如何在状态更改时运行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56550713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com