In my app, I’ve a TextField {that a} consumer can enter a number of traces of textual content into. I might like to have the ability to place a Button proper subsequent to the TextField, however am unable to do that as a result of SwiftUI will power the TextField to take up as a lot house as attainable horizontally i.e:
HStack
{
TextField("", textual content: self.$textFieldUserInput, axis: .vertical).lineLimit(1...).centered(self.$textFieldIsFocused)
Button(""){}.buttonStyle(.borderedProminent)
Spacer()
}
will result in:
After I’m wanting this:
I’ve give you a good work round that replaces the TextField when it isn’t centered with a Textual content element:
ZStack(alignment: .main)
{
TextField("", textual content: self.$textFieldUserInput, axis: .vertical)
.lineLimit(1...)
.centered(self.$textFieldIsFocused)
.opacity(self.textFieldIsFocused ? 1 : 0)
if (!self.textFieldIsFocused)
{
HStack
{
Textual content(self.textFieldUserInput)
.onTapGesture
{
self.textFieldIsFocused = true
}
Button(""){}.buttonStyle(.borderedProminent)
}
}
}
The downside to that is that now it’s a must to faucet the Textual content element to activate the TextField so the consumer cannot particularly resolve the place they need the cursor to begin (and likewise when the TextField is lively you both need to make the Button disappear or dwell with it being shifted all the best way to the correct once more).
Edit: I’ve tried a lot of the options (SwiftUI TextField takes max width and dynamically regulate the width of a TextField to its content material?) that contain utilizing fixedSize, however that does not work if you need multiline textual content and have to make use of axis: .vertical within the TextField.
Am questioning if there’s a higher approach to accomplish this, to one way or the other make a TextField in SwiftUI measurement to suit so you possibly can place a button instantly subsequent to it?


