Search code examples
iosswiftswiftui

SwiftUI - How can a TextField increase dynamically its height based on its content?


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!!!!


Solution

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