tl;dr: UITextView does not auto layout when isScrollEnabled = false
I have a screen with multiple UITextViews on it, contained within a ScrollView. For each textview, I calculate the height needed to display the entire content in SwiftUI and set it using the .frame(width:height:)
modifier.
The UITextView will respect the size passed in and layout within the container, but since UITextView is embedded within a UIScrollView, when a user attempts to scroll on the page, often they will scroll within a UITextView block rather than the page. They currently need to scroll along the margins outside of the textview to get the proper behavior.
Since I am already calculating the height to display the text, I don't want the UITextView to scroll. However, when I set isScrollEnabled = false
, the text view displays in a single long line that gets truncated. I have tried
- Setting various frame/size attributes but that seems to have zero affect on the layout.
- Embedding the textView within a UIView, and then sizing the container, but then the textView does not display at all.
- Setting a fixed size textContainer in the layoutManager but did not work.
There's a lot of code so I can't copy/paste it all, but generally, it looks like
struct SwiftUITextEditor: View {
@State var text: AttributedString = ""
var body: some View {
ZStack {
MyTextViewRepresentable(text: $text)
}
.dynamicallySized(from: $text)
}
}
struct MyTextViewRepresentable: UIViewRepresentable {
@Binding var text: AttributedString
let textView = UITextView(usingTextLayoutManager: true)
func makeUIView(context: Context) -> UITextView {
textView.attributedText = text
textView.isScrollEnabled = false
}
...
}