我在下面的代碼中有一個問題,每當我使用 Toggle()-Button 時,SettingsEx1View 都會消失,Exercise1View() 會出現。它們與 ObservableObject Profile() 相連。啟動應用程式時出現此錯誤,但似乎這是 Apple 必須修復的 SwiftUI 錯誤。奇怪的是,當我洗掉第 18 和 19 行時
let osc = DynamicOscillator()
let audioEngine = AudioEngine()
它作業得很好。有什么我忽略的或者你知道我能做些什么嗎?任何幫助表示贊賞,謝謝!
import SwiftUI
import AVFoundation
import AudioKit
import SoundpipeAudioKit
import Foundation
class Profile: ObservableObject {
@Published var playSoundeffects = true
@Published var waveformIndex = 0
}
struct Exercise1View: View {
@EnvironmentObject var profile: Profile
let osc = DynamicOscillator()
let audioEngine = AudioEngine()
var body: some View {
NavigationLink(
destination: SettingsEx1View())
{
Image(systemName: "gearshape.circle")
}
.navigationTitle("Exercise1")
}
}
struct SettingsEx1View: View {
@EnvironmentObject var profile: Profile
let waveformOptions = ["sine", "triangle", "sawtooth", "square"]
var body: some View {
Form {
Section(header: Text("General")) {
Toggle("play soundeffects", isOn: $profile.playSoundeffects)
Picker("waveform", selection: $profile.waveformIndex) {
ForEach(0 ..< waveformOptions.count) {
Text(self.waveformOptions[$0])
}
}
}
}
.navigationTitle("Settings")
}
}
struct HomeScreen: View {
@EnvironmentObject var profile: Profile
@AppStorage("playSoundeffects") var playSoundeffectsSave: Bool = true
@AppStorage("waveform") var waveformIndexSave: Int = 0
var body: some View {
NavigationView{
NavigationLink(destination: Exercise1View())
{Text("Exercise1")}
}
.onAppear {
profile.playSoundeffects = playSoundeffectsSave
profile.waveformIndex = waveformIndexSave
}
.onChange(of: profile.playSoundeffects) { newValue in
playSoundeffectsSave = profile.playSoundeffects
}
.onChange(of: profile.waveformIndex) { newValue in
waveformIndexSave = profile.waveformIndex
}
}
}
struct ContentView: View {
var body: some View {
HomeScreen()
.environmentObject(Profile())
}
}
uj5u.com熱心網友回復:
HomeScreen.body取決于設定,因此Profile當后者更新時,它會被重繪 并作為NavigationView的一部分重新創建body,因此它的導航堆疊被破壞。
由于NavigationView不依賴于Profile自身,最簡單的解決方案是將其分離為獨立視圖,例如
struct HomeScreen: View {
// ... other code
var body: some View {
MainView()
.onAppear {
profile.playSoundeffects = playSoundeffectsSave
// ... other code
}
struct MainView: View {
var body: some View {
NavigationView{ // << here !!
NavigationLink(destination: Exercise1View())
{Text("Exercise1")}
}
}
}
有關更多資訊,另請參閱:https ://stackoverflow.com/a/72824345/12299030
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497948.html
