I made a dynamic height text editor using the following code and it works fine, the issue is when I finish entering the text I will save it to Text View then when I want to edit the text in the Text View using the same dynamic height text editor it doesn't expand to fit the text (doesn't increase its height) every time I edit the text sometimes it does and sometimes it stills the same original height as shown in the photo below.
Dynamic Height Text Editor
struct DynamicHeightTextEditor: UIViewRepresentable {
typealias UIViewType = UITextView
@Binding var text: String
@Binding var height: CGFloat
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.text = text
textView.font = UIFont.systemFont(ofSize: 17)
textView.textColor = UIColor.label
textView.backgroundColor = .clear
textView.delegate = context.coordinator
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
DispatchQueue.main.async {
if height == 0 {
withAnimation(.default) {
height = textView.contentSize.height
}
}
if text == "" {
textView.text = ""
}else{
textView.text = text
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: DynamicHeightTextEditor
init(parent: DynamicHeightTextEditor) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
DispatchQueue.main.async {
self.parent.height = textView.contentSize.height
self.parent.text = textView.text
}
}
}
}
Using the Dynamic Height Text editor in SwiftUI
DynamicHeightTextEditor(text: $taskModel.text, height: $toolBarViewModle.textEditorHeight)
.font(.system(.body))
.foregroundColor(Color(.label))
.multilineTextAlignment(.leading)
.frame(minWidth: 0, maxWidth: .infinity)
// To limit view height
.frame(height: toolBarViewModle.textEditorHeight <= 60 ? toolBarViewModle.textEditorHeight : 76)
.clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
.background(roundedBackground)
.focused($isTextFieldFocused)
.padding(EdgeInsets(top: 8, leading: 48, bottom: 8, trailing: 16))
// To Reset view height when finish enter text to text editor
.onChange(of: toolBarViewModle.toolBarState == .none) { _ in
toolBarViewModle.textEditorHeight = 0
}