6

I'm getting really close to implementing dynamic height for a UITextView in SwiftUI. Please help me work out these kinks:

  1. The UITextView has the correct height when it appears but does not adjust height as editing is being performed; I would like it to adjust.
  2. I'm receiving this in the console every time I edit the text in the TextView: [SwiftUI] Modifying state during view update, this will cause undefined behavior.

Here's my code:

ItemEditView

TextView(text: $notes, textViewHeight: $textViewHeight)
    .frame(height: self.textViewHeight)

UITextView

import SwiftUI

struct TextView: UIViewRepresentable {
    @Binding var text: String
    @Binding var textViewHeight: CGFloat

    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.delegate = context.coordinator
        textView.font = .systemFont(ofSize: 17)
        textView.backgroundColor = .clear

        return textView
    }

    func updateUIView(_ textView: UITextView, context: Context) {
        textView.text = text
    }

    class Coordinator: NSObject, UITextViewDelegate {
        var control: TextView

        init(_ control: TextView) {
            self.control = control
        }

        func textViewDidChange(_ textView: UITextView) {
            control.text = textView.text
        }
    }

    func makeCoordinator() -> TextView.Coordinator {
        Coordinator(self)
    }
}

Similar questions have been asked, but none of the solutions worked for me.

atdonsm
  • 265
  • 4
  • 11
  • 2
    The following topic should be helpful [How do I create a multiline TextField in SwiftUI?](https://stackoverflow.com/questions/56471973/how-do-i-create-a-multiline-textfield-in-swiftui/58639072#58639072) – Asperi Mar 18 '20 at 03:36
  • Thanks, Asperi! I would have commented on your post but don't have enough points yet. I'm getting the following error: "Variable 'self.item' used before being initialized" on the line "self._showingPlaceholder = State(initialValue: self.text.isEmpty)". Any ideas? – atdonsm Mar 18 '20 at 10:44
  • 1
    There is no `self.item` in my code, so I have no idea. – Asperi Mar 18 '20 at 10:52
  • You're right––that was my mistake. I'm presenting the TextView in a sheet, and now I'm getting this error when I call my View: "Missing argument for parameter 'text' in call / Insert 'text: <#Binding#>, '" Is there any way to get rid of this? I don't want to pass in a binding from that view. – atdonsm Mar 18 '20 at 11:59
  • Asperi, have you found a solution for the caret jumping to the end of the TextView when adding/removing paragraphs? – atdonsm Mar 21 '20 at 13:18
  • I found a great approach here https://shadowfacts.net/2020/swiftui-expanding-text-view/, and that worked for me too. – Abdhi P Dec 19 '22 at 12:44

0 Answers0