@observedobject Decorates an object, that is, decorates an object. This object can be used by other classes. But this class first follows the ObervableObject protocol and the internal variables are decorated with ** @published **.
Declare an object server object
Import Foundation import Combine Final class PodcastPlayer: ObservableObject { @Published private(set) var isPlaying: Bool = false func play() { isPlaying = true } func pause() { isPlaying = false } }Copy the code
In the code above, declare a player. The isPlaying property of this class cannot be modified externally. This can only be modified in two ways.
Let’s use this class:
Create a View
struct ProductView: View { @ObservedObject var player: PodcastPlayer var body: some View { Button (action: { if player.isPlaying { player.pause() }else { player.play() } }) { let buttonTitle = player.isPlaying ? Text(buttonTitle)}}Copy the code
ObservedObject Var player: PodcastPlayer uses player declarations in the current class. You need to pass a default player in the ProductView, or else you will get an error:
struct ContentView: View {
@StateObject private var modelData = ModelData()
var body: some View {
ProductView(player: PodcastPlayer())
}
}
Copy the code
At this point we run the code: click the button and the title of the button changes. We call player.play and pause methods to change the value of isPlaying. The UI of the corresponding referenced location is also refreshed