I'm trying to integrate a UISegmentedControl into my view, which works fine. But I want to update the SwiftUI ContentView when the control's index changes.
For this purpose I want to create a Coordinator for accessing the ContentView's State through a Binding.
I followed the official
(relevant from min 13:37), but it throws out an error saying "Cannot assign to property: '$textString' is immutable" when I try to implement the init function of the Coordinator class.
import SwiftUI
import UIKit
struct SegControl: UIViewRepresentable {
class Coordinator: NSObject {
@Binding var textString: String
init(textString: Binding<String>) {
//Error: Cannot assign to property: '$textString' is immutable
$textString = textString
}
@objc func testFunc() {
textString = "Updated!"
}
}
@Binding var textString: String
func makeCoordinator() -> Coordinator {
return Coordinator(textString: $textString)
}
func makeUIView(context: Context) -> UISegmentedControl {
return UISegmentedControl(items: ["One", "Two"])
}
func updateUIView(_ uiView: UISegmentedControl, context: Context) {
uiView.center = uiView.center
uiView.selectedSegmentIndex = 0
uiView.addTarget(context.coordinator, action: #selector(Coordinator.testFunc), for: .valueChanged)
}
}