I need to do a bit of customisation on a UITextView so I am creating a custom UIViewRepresentable to wrap the UITextView.
One of these is that the input should be centred and not wrap.
Searching on how to disable wrapping gives various conflicting recommendations, from not using UITextView to wrapping it in a UIScrollView. None of these seem to work reliably.
It seems like all that is required, is setting the size of the text container to be sufficiently wide but this is also not working. Below is what I've tried so far but it does not wrap the view.
The InputView also seems to take up the entire height of the screen. I have a feeling this is fundamentally part of my problem.
What am I missing?
import SwiftUI
struct InputView: UIViewRepresentable {
@Binding var text: String
typealias UIViewType = UITextView
func makeUIView(context: Context) -> UIViewType {
// Setup text view:
// ----------------
let textView = UITextView()
textView.textAlignment = .center
textView.delegate = context.coordinator
textView.font = UIFont.systemFont(ofSize: 72)
textView.textContainer.widthTracksTextView = false
textView.textContainer.size = CGSize(width: 20000, height: CGFloat.greatestFiniteMagnitude)
textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return textView
}
func makeCoordinator() -> InputView.Coordinator {
return Coordinator(self)
}
func updateUIView(_ textView: UIViewType, context: Context) {
if textView.text != text {
textView.text = text
}
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: InputView
init(_ parent: InputView) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
parent.text = textView.text
}
}
}
struct ContentView: View {
@State private var input: String = "ShouldNotWrapButScrollHorizontally"
var body: some View {
InputView(text: $input)
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}