简体   繁体   中英

Play audio on selection list in SwiftUI

I'm developing a simple app where the list of sounds is available and by tapping on it that sound should play.
For that, I've created below SwiftUI view. But didSet() of selectedSound is never being called.

import SwiftUI

struct SoundList: View {
    let category: Category
    @State private var selectedSound: String? {
        didSet {
            if let selectedSound {
                AudioManager.shared.playAudio(withFilename: selectedSound)
            }
        }
    }

    var body: some View {
        VStack {
            Text(selectedSound ?? "N/A") // Just to check if selection is working or not
            List(category.sounds, id: \.self, selection: $selectedSound) { sound in
                Text(sound)
            }
        }
        .navigationTitle(category.name)
    }
}

struct SoundList_Previews: PreviewProvider {
    static var previews: some View {
        SoundList(category: Category.getAllData().first!)
    }
}

I'm sure my AudioManager class is working fine, so there is no any faulty code for playing audio. What Am I missing here? Stateful variables never called it's didSet() ? if yes then what will be workaround this kind of scenario?

Don't use didSet , use .onChange(of:){} instead. Like this:

    @State private var selectedSound: String?

    var body: some View {
        VStack {
            Text(selectedSound ?? "N/A") // Just to check if selection is working or not
            List(category.sounds, id: \.self, selection: $selectedSound) { sound in
                Text(sound)
            }
        }
        .navigationTitle(category.name)

        // Here:
        .onChange(of: selectedSound) { value in
            if let value {
                AudioManager.shared.playAudio(withFilename: value)
            }
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM