“This Binding syntax for declaring a binding works better in this not-strictly-SwiftUI setting, but this might be a bug.”
I’m confused, can you help me understand what this means?
“This Binding syntax for declaring a binding works better in this not-strictly-SwiftUI setting, but this might be a bug.”
I’m confused, can you help me understand what this means?
hi Bill! the usual way to declare a binding is @Binding
, but that didn’t work, at the time I wrote this chapter. I can’t see any reason why it shouldn’t, so I thought it might be something that Apple will fix eventually.
SwiftUI is still evolving
Audry, thanks for the reply. After digging into this further, I decided to apply another pattern that seems to be common when Coordinator is being used for target/action.
import SwiftUI
import UIKit
struct ColorUISlider: UIViewRepresentable {
class Coordinator: NSObject {
var slider: ColorUISlider
init(_ slider: ColorUISlider) {
self.slider = slider
}
@objc func valueChanged(_ sender: UISlider) {
slider.value = Double(sender.value)
}
}
var color: UIColor
@Binding var value: Double
func makeCoordinator() -> ColorUISlider.Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> UISlider {
let slider = UISlider(frame: .zero)
slider.thumbTintColor = color
slider.value = Float(value)
slider.addTarget(context.coordinator,
action: #selector(Coordinator.valueChanged(_:)), for: .valueChanged)
return slider
}
func updateUIView(_ uiView: UISlider, context: Context) {
uiView.value = Float(self.value)
}
}
struct ColorUISliderPreviews: PreviewProvider {
static var previews: some View {
ColorUISlider(color: .red, value: .constant(0.5))
}
}
Thanks again.
Bill
thanks Bill! that looks really straightforward — I think this is one of the things that started out a little complicated before they got around to making it simpler.