Disable Line Wrapping in UITextView wrapped in UIViewRepresentable

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()
  }
}
Answered by Ken Chung in 682623022

You can wrap it inside a SwiftUI ScrollView instead.

ScrollView {
  InputView(text: $input)
      .padding()
}

You'll also need to disable scrolling of the TextView. To do that, add this inside makeUIView().

textView.isScrollEnabled = false
Accepted Answer

You can wrap it inside a SwiftUI ScrollView instead.

ScrollView {
  InputView(text: $input)
      .padding()
}

You'll also need to disable scrolling of the TextView. To do that, add this inside makeUIView().

textView.isScrollEnabled = false
Disable Line Wrapping in UITextView wrapped in UIViewRepresentable
 
 
Q