Wednesday, December 17, 2025
HomeiOS DevelopmentIs there a approach to get a TextField to measurement to suit...

Is there a approach to get a TextField to measurement to suit so I can put a button instantly subsequent to it? [duplicate]


In my app, I’ve a TextField {that a} person can enter a number of traces of textual content into. I would 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 drive the TextField to take up as a lot area as attainable horizontally i.e:

HStack
{
    TextField("", textual content: self.$textFieldUserInput, axis: .vertical).lineLimit(1...).targeted(self.$textFieldIsFocused)
    Button(""){}.buttonStyle(.borderedProminent)
    Spacer()
}

will result in:

Is there a approach to get a TextField to measurement to suit so I can put a button instantly subsequent to it? [duplicate]

Once I’m wanting this:

enter image description here

I’ve provide you with a good work round that replaces the TextField when it isn’t targeted with a Textual content part:

ZStack(alignment: .main)
{
    TextField("", textual content: self.$textFieldUserInput, axis: .vertical)
    .lineLimit(1...)
    .targeted(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 part to activate the TextField so the person cannot particularly determine the place they need the cursor to start out (and likewise when the TextField is energetic you both must make the Button disappear or stay with it being shifted all the best way to the suitable once more).

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’ll be able to place a button instantly subsequent to it?

RELATED ARTICLES

Most Popular

Recent Comments