0

I wanted to extend my SwiftUI application so that I can use the TextView from UIKit as it's currently not available in SwiftUI so I copied this code from Stackoverflow:

import Foundation
import SwiftUI
import UIKit

struct EditableTextView: UIViewRepresentable {

@Binding var text: String
@Binding var textStyle: UIFont.TextStyle

func makeUIView(context: Context) -> UITextView {
    let textView = UITextView()

    textView.font = UIFont.preferredFont(forTextStyle: textStyle)
    textView.autocapitalizationType = .sentences
    textView.isSelectable = true
    textView.isUserInteractionEnabled = true

    return textView
}

func updateUIView(_ uiView: UITextView, context: Context) {
    uiView.text = text
    uiView.font = UIFont.preferredFont(forTextStyle: textStyle)
}
}

I'm using it just like this:

struct ConvertView: View {

@State var userText: String = ""
@State private var textStyle = UIFont.TextStyle.body

var body: some View {
    //...
    EditableTextView(text: $userText, textStyle: $textStyle)
    //...
}
}

The result is a textView that looks just like the one in UIKit. I assume that whenever the user writes something in this textView, the text gets saved to userText. But that doesn't happen. Why?

I have found out that updateUIView actually does not get called every time the user writes something in the textView. What's happening makes sense to me, but I don't know how to solve it. I just want to get the text that's in the textView when the user presses a button, not more.

Thanks for your answers.

Q G
  • 1
  • 1

0 Answers0