当状态改变时如何运行操作? [英] How can I run an action when a state changes?

查看:22
本文介绍了当状态改变时如何运行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)")?我查看了文档,然后找不到任何东西.

How do I run code (e.g print("Selection changed to (selection)") when the $selection state changes? I looked through the docs and I couldn't find anything.

推荐答案

你不能在 @State 上使用 didSet 观察者,但你可以在 ObservableObject 上使用 属性.

You can't use didSet observer on @State but you can on an ObservableObject property.

import SwiftUI
import Combine

final class SelectionStore: ObservableObject {
    var selection: SectionType = .top {
        didSet {
            print("Selection changed to (selection)")
        }
    }

    // @Published var items = ["Jane Doe", "John Doe", "Bob"]
}

然后像这样使用它:

import SwiftUI

enum SectionType: String, CaseIterable {
    case top = "Top"
    case best = "Best"
}

struct ContentView : View {
    @ObservedObject var store = SelectionStore()

    var body: some View {
        List {
            Picker("Selection", selection: $store.selection) {
                ForEach(FeedType.allCases, id: .self) { type in
                    Text(type.rawValue).tag(type)
                }
            }.pickerStyle(SegmentedPickerStyle())

            // ForEach(store.items) { item in
            //     Text(item)
            // }
        }
    }
}

这篇关于当状态改变时如何运行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆