Home > AI > IOS > SwiftUI >

onChange(of:perform:)

Example:

struct Episode {
    var title: String = "Black Widow"
}
enum PlayState: String {
    case play
    case paused
}

class ContentViewModel: ObservableObject {
    func playStateDidChange(from: PlayState, to: PlayState) {
        print(from, to)
    }
}

struct ContentView : View {
    var episode = Episode()
    @State private var playState: PlayState = .paused
    @ObservedObject var model = ContentViewModel()

    var body: some View {
        VStack {
            Text(episode.title)
            Button {
                switch playState {
                case .paused:
                    playState = PlayState.play
                case .play:
                    playState = PlayState.paused
                }
            } label: {
                Text(playState.rawValue)
            }

        }
        .onChange(of: playState) { [playState] newState in
            model.playStateDidChange(from: playState, to: newState)
        }
    }
}

Leave a Reply