Search code examples
iosswiftswiftuiswiftui-list

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?


Solution

  • 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)
                }
            }
    
        }
    }