Im trying to do custom message text field in SwiftUI. When I start typing into the text field, everything is ok. I can hit enter and jump to newline without any issues, but when I reach the end of the line, the text disappears.
Here is the code:
struct MessageInputField: UIViewRepresentable {
var inputMessage: Binding<String>
var currentFieldHeight: Binding<CGFloat>
func makeUIView(context: Context) -> UITextView {
let textView = UITextView(frame: .zero)
textView.isScrollEnabled = false
textView.font = UIFont.systemFont(ofSize: 15)
textView.delegate = context.coordinator
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.setContentHuggingPriority(.defaultHigh, for: .vertical)
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = inputMessage.wrappedValue
updateTextViewHeight(uiView)
}
private func updateTextViewHeight(_ textView: UITextView) {
let size = textView.sizeThatFits(CGSize(width: textView.frame.width, height: .greatestFiniteMagnitude))
// Calculate max height for 5 lines
let maxHeight = textView.font!.lineHeight * 5
// Limit textView height and enable scrolling when content exceeds max height
if size.height >= maxHeight {
currentFieldHeight.wrappedValue = maxHeight
textView.isScrollEnabled = true
if textView.frame.size.height != maxHeight {
textView.frame.size.height = maxHeight
}
} else {
currentFieldHeight.wrappedValue = size.height
textView.isScrollEnabled = false
if textView.frame.size.height != size.height {
textView.frame.size.height = size.height
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: MessageInputField
init(_ parent: MessageInputField) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
parent.inputMessage.wrappedValue = textView.text
parent.updateTextViewHeight(textView)
}
}
}
Here is the issue: