2

I am trying to build a "chat" view using SwiftUI and I would like to know how can I do in order to increase the height dynamically of a TextField where the users should write their messages.

I have defined a minHeight expecting that the TextField could increase its height based on its intrinsic content.

My current view code:

struct MessageSenderView: View {
    @Binding var userTextInput: String

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: 17) {
                senderPlusImage()
                ZStack {
                    Capsule()
                        .fill(Color("messagesBankDetailColor"))
                        .frame(minHeight: 34, alignment: .bottom)
                    HStack(spacing: 15){
                        Spacer()
                        ZStack(alignment: .leading) {
                            if userTextInput.isEmpty { Text(Constants.Login.Text.userPlaceHolder).foregroundColor(Color.white) }
                            TextField(" ", text: $userTextInput)
                                .multilineTextAlignment(.leading)
                                .frame(minHeight: CGFloat(34))
                                .foregroundColor(Color.white)
                                .background(Color("messagesBankDetailColor"))
                                .onAppear { self.userTextInput = "" }
                        }
                        arrowImage()
                    }
                    .frame(minHeight: CGFloat(34))
                    .padding(.trailing, 16)
                    .layoutPriority(100)
                }
            }
            .padding(16)
        }
        .background(Color("mainBackgroundColor"))
    }
}

And here is how it looks like:

enter image description here

Thank you!!!!

Andoni Da Silva
  • 925
  • 10
  • 23
  • 1
    The approach from the topic [How do I create a multiline TextField in SwiftUI?](https://stackoverflow.com/a/58639072/12299030) can be helpful. – Asperi Feb 14 '20 at 08:59

2 Answers2

2

For this purpose, you should use UITextfield with the UIViewRepresentable protocol. Maybe this tutorial can help you : Dynamic TextField SwiftUI

Mac3n
  • 3,455
  • 2
  • 15
  • 27
2

To support multiline text, you should use TextEditor instead of TextField.

If you want it to grow as you type, embed it with a label like below:

ZStack {
    TextEditor(text: $text)
    Text(text).opacity(0).padding(.all, 8) // <- This will solve the issue if it is in the same ZStack
}

Demo

Demo

Mojtaba Hosseini
  • 71,072
  • 19
  • 226
  • 225