我有一个 Published 变量,该变量在调用函数时会发生变化。我在类中打印变量,我可以看到它已经设置了变量,但是当它没有改变我的视图时,当我打印变量时,它只打印我最初设置变量的内容。
我知道在这方面有几个类似的帖子,但是在浏览完它们之后,我仍然不确定我做错了什么。
代码如下:(减去我认为在这里不相关的位)
包含被调用以更改变量的函数的类
class MusicManager: NSObject, ObservableObject {
@Published var playlistLabel: String = "N/A"
func playPlaylistNow(chosenPlaylist: String?) {
...
playlistLabel = chosenPlaylist!
print(playlistLabel) // I get the revised variable printed here
}
}
查看更新
struct HomeView: View {
...
@ObservedObject var musicManager: MusicManager = MusicManager()
var body: some View {
...
SongLabels(trackLabel: currentTrack!, artistLabel: currentArtist!, playlistLabel: musicManager.playlistLabel)
...
}
...
.onAppear {
self.updateTrackData()
}
}
func updateTrackData() {
print("Playlist: \(musicManager.playlistLabel)") // I get the original "N/A" printed here
}
调用函数的视图:
{
@State private var showingAlert = false
let musicManager: MusicManager = MusicManager()
var playlistName: String
var body: some View {
Button(action: {
self.showingAlert = true
self.musicManager.playPlaylistNext(chosenPlaylist: self.playlistName)
}) {
Text("Play Next")
}
.alert(isPresented: $showingAlert) {
...
}
...
}
}