Home > other >  What State/Binding do I need to use?
What State/Binding do I need to use?

Time:08-16

I want to create a Timer that is showing in a Slider. I got this Code:

struct CustomSlider : View {
    @State var value: Double = 0.0
    init() {
        let thumbImage = UIImage(systemName: "circle.fill")
        UISlider.appearance().setThumbImage(thumbImage, for: .normal)
    }
    
    var body: some View {
        Slider(value: $value)
    }
}
struct MusicPlayerView: View {
    @State var value: Double = 0.0
    
    let timer = Timer
        .publish(every: 0.5, on: .main, in: .common)
        .autoconnect()
    
    var body: some View {
            CustomSlider()
.onReceive(timer) { _ in
                    guard let player = audioManager.player else {return}
                    value = player.currentTime
                }
    }
}

How do I pass the value from MusicPlayerView to CustomSlider? I tried using @Bindingin the CustomSliderbut then it gives me the error:

Return from initializer without initializing all stored properties

in CustomSlider

CodePudding user response:

When using @Binding you need to update your init:

struct CustomSlider : View {
    @Binding var value: Double
    init(value: Binding<Double>) {
        self._value = value
        let thumbImage = UIImage(systemName: "circle.fill")
        UISlider.appearance().setThumbImage(thumbImage, for: .normal)
    }
    
    var body: some View {
        Slider(value: $value)
    }
}

And in MusicPlayerView:

struct MusicPlayerView: View {
    @State var value: Double = 0.0
    
    let timer = Timer
        .publish(every: 0.5, on: .main, in: .common)
        .autoconnect()
    
    var body: some View {
            CustomSlider(value: $value)
.onReceive(timer) { _ in
                    guard let player = audioManager.player else {return}
                    value = player.currentTime
                }
    }
}
  • Related