2

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

WWDC video

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


}
dalton_c
  • 6,876
  • 1
  • 33
  • 42
Womble Tristes
  • 393
  • 1
  • 4
  • 14
  • Beta 4 broke my `UIImagePickerController` port. It was based on this question, and I see that the answer's been updated for the fix: https://stackoverflow.com/questions/56515871/how-to-open-the-imagepicker-in-swiftui/57160706#57160706 Hopefully this helps you. Remember, basically `UIViewRepresentable` and `UIViewControllerRepresentable` are the same thing - a single SwiftUI `View`. –  Jul 23 '19 at 21:52
  • 1
    This is answered here: https://stackoverflow.com/questions/56973959/swiftui-how-to-implement-a-custom-init-with-binding-variables, but the TL;DR is just to replace the $ with _, like so: $textString = textString // beta 3 _textString = textString // beta 4 – KRH Jul 24 '19 at 00:26

0 Answers0