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
  • 1,161
  • 15
  • 31
  • 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

3 Answers3

3

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
  • 95,414
  • 31
  • 268
  • 278
3

In latest update of SwiftUI this is solved ,

TextField("This is Placeholder", text: $text, axis: .vertical)

it also how big the textfiled will grow.

LeoNard
  • 230
  • 1
  • 9
2

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

colllin
  • 9,442
  • 9
  • 49
  • 65
Mac3n
  • 4,189
  • 3
  • 16
  • 29