Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Prevent TextField from expanding when text is entered

Tags:

ios

swift

swiftui

I have a TextField with a fixed-size frame, but it still expands to wrap the entered text, even over siblings.

Initial state:

Initial TextField

With some input:

TextField with input

Is there a way to prevent this in SwiftUI using TextField or do I need to resort to ViewRepresentable?

My code for this layout looks something like:

HStack(spacing: 0) {
    Text("1").fixedSize(horizontal: true, vertical: false).frame(width: 22)
    TextField("Price", text: $text1).fixedSize(horizontal: true, vertical: false).frame(width: 70)
    TextField("1", text: $text2).fixedSize(horizontal: true, vertical: false).frame(width: 30)
    TextField("1", text: $text3).fixedSize(horizontal: true, vertical: false).frame(width: 70)
}.textFieldStyle(RoundedBorderTextFieldStyle())
like image 674
Stevie Kideckel Avatar asked Sep 02 '25 14:09

Stevie Kideckel


1 Answers

Change order of modifiers, like

TextField("1", text: $text3)
   .frame(width: 70)                                // << here !!
   .fixedSize(horizontal: true, vertical: false)

Tested with Xcode 12.1 / iOS 14.1

like image 90
Asperi Avatar answered Sep 05 '25 05:09

Asperi