Reputation: 1321
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:
Thank you!!!!
Upvotes: 4
Views: 7033
Reputation: 136
TextField("Write a message", text: $newMessage, axis: .vertical)
.textFieldStyle(.roundedBorder)
.lineLimit(5)
.submitLabel(.return)
It will grew maximum respected to no of lines. After that it will scroll content inside.
Upvotes: 0
Reputation: 290
In latest update of SwiftUI this is solved ,
TextField("This is Placeholder", text: $text, axis: .vertical)
Textfiled will grow depending on the text size and lines.
Upvotes: 7
Reputation: 4719
For this purpose, you should use UITextfield with the UIViewRepresentable
protocol.
Maybe this tutorial can help you : YouTube: Dynamic TextField SwiftUI
Upvotes: 2
Reputation: 119128
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
}
Upvotes: 4