In my app, I have a TextField that a user can enter multiple lines of text into. I'd like to be able to place a Button right next to the TextField, but am unable to do this because SwiftUI will force the TextField to take up as much space as possible horizontally i.e:
HStack
{
TextField("", text: self.$textFieldUserInput, axis: .vertical).lineLimit(1...).focused(self.$textFieldIsFocused)
Button(""){}.buttonStyle(.borderedProminent)
Spacer()
}
will lead to:
When I'm wanting this:
I've come up with a decent work around that replaces the TextField when it's not focused with a Text component:
ZStack(alignment: .leading)
{
TextField("", text: self.$textFieldUserInput, axis: .vertical)
.lineLimit(1...)
.focused(self.$textFieldIsFocused)
.opacity(self.textFieldIsFocused ? 1 : 0)
if (!self.textFieldIsFocused)
{
HStack
{
Text(self.textFieldUserInput)
.onTapGesture
{
self.textFieldIsFocused = true
}
Button(""){}.buttonStyle(.borderedProminent)
}
}
}
The drawback to this is that now you have to tap the Text component to activate the TextField so the user can't specifically decide where they want the cursor to start (and also when the TextField is active you either have to make the Button disappear or live with it being shifted all the way to the right again).
Am wondering if there is a better way to accomplish this, to somehow make a TextField in SwiftUI size to fit so you can place a button directly next to it?

