I would like to show a TextField
inside a Form
in an inspector.
Here is my code, and I am using a Section
since there will be many more controls.
struct TestView: View {
@State private var inspectorShown = true
@State private var text = "ABCDE"
var body: some View {
Text("Hello")
.inspector(isPresented: $inspectorShown) {
Form {
Section {
TextField("", text: $text)
.textFieldStyle(.roundedBorder)
}
}
}
}
}
This is what it looks like:
As you can see, the text is aligned to the right and the TextField
doesn't use the full width.
How can I fix this?
Try applying .labelsHidden()
:
Section("Test") {
TextField("", text: $text)
.textFieldStyle(.roundedBorder)
.labelsHidden() // 👈 here
// .multilineTextAlignment(.leading) // not needed
}
The alignment can be controlled by applying the modifier .multilineTextAlignment
, but when the label is hidden it seems to use leading alignment anyway:
When the modifier .labelsHidden
is not used, the modifier .multilineTextAlignment
seems to have no effect. In other words, when the label is shown, the alignment is always trailing.
If you decide you want to show a label after all, but keep leading alignment for the TextField
, a workaround is to wrap the TextField
as LabeledContent
:
Section("Test") {
LabeledContent("Label") {
TextField("", text: $text)
.textFieldStyle(.roundedBorder)
.labelsHidden()
.multilineTextAlignment(.leading)
}
}