Home / IOS Development / ios – SwiftUI Why does context.coordinator.value.wrappedValue provide only the original value?

ios – SwiftUI Why does context.coordinator.value.wrappedValue provide only the original value?



I’m trying to implement some UIKit components in my SwiftUI app. I have added UISlider to the SwiftUI view. But one thing bugs me. When I move the slider, the value updates ok, but I̵

7;m curious why context.coordinator.value.wrappedValue stays the same? Here is my implementation:

import SwiftUI

struct UISliderView: UIViewRepresentable {
typealias UIViewType = UISlider

@Binding var value: Double
var minValue: Double
var maxValue: Double

func makeUIView(context: Context) -> UISlider {
    let slider = UISlider(frame: .zero)
    slider.maximumValue = Float(minValue)
    slider.maximumValue = Float(maxValue)
    slider.value = Float(value)
    slider.addTarget(context.coordinator,
                     action: #selector(Coordinator.valueChanged(_:)),
                     for: .valueChanged)
    return slider
}

func updateUIView(_ uiView: UISlider, context: Context) {
    print("Value: (value)")
    print("Wrapped value: (context.coordinator.value.wrappedValue)")
    uiView.value = Float(value)
}

func makeCoordinator() -> Coordinator {
    let coordinator = Coordinator(value: $value)
    coordinator.id = 5
    return coordinator
}

class Coordinator: NSObject {
    var value: Binding
    var id: Int = 0
    
    init(value: Binding) {
        self.value = value
    }
    
    @objc func valueChanged(_ sender: UISlider) {
        value.wrappedValue = Double(sender.value)
    }
}
}

This is a part that bothers me:

print("Value: (value)")
print("Wrapped value: (context.coordinator.value.wrappedValue)")

These values ​​should be the same, or at least I expect them to be the same, but still they are not?


Source link