I need a SwiftUI multiline text input control for MacOS satisfying the following requirements:
I tried using TextField with lineLimit() modifier which looks exactly how I need it, i.e. the label is showing correctly (incl. alignment), but it only has a height of 1 line if it's empty and the RETURN key doesn't do what I want (i.e. new line):
struct ContentView: View {
@State var field1 = ""
@State var field2 = ""
@State var notes = ""
var body: some View {
Form {
TextField("Label", text: $field1)
TextField("Long Label", text: $field2)
TextField("Notes", text: $notes)
.lineLimit(10)
}
.padding()
.frame(height: 150)
}
}
Then I tried a TextEditor, but this lacks the ability to define a label. The placement of the label is what makes the Form element extremly usefull for MacOS as it allows the right alignment of the labels without any hacks. The missing border style is only a small issue that can probably solved using border styles:
struct ContentView: View {
@State var field1 = ""
@State var field2 = ""
@State var notes = ""
var body: some View {
Form {
TextField("Label", text: $field1)
TextField("Long Label", text: $field2)
TextEditor(text: $notes)
}
.padding()
.frame(height: 150)
}
}
I'm only interested in a clean solution that is future-proof. If there's none, a hack must be at least very flexible, i.e. all the labels must be correctly aligned. The solution from workingdog doesn't fit for me, because as soon as the label text changes, everything falls apart.
This is a partial solution,
Form
{
TextField("Title", text: .constant("Foo"))
LabeledContent("Label")
{
TextEditor(text: .constant("My\nText\nView"))
}
}
The word "Label" will appear in the label position in the form correctly justified and aligned vertically and horizontally.
Unfortunately, the TextEditor
field itself is vertically displaced downwards slightly and I lack the SwiftUI expertise to fix it. If I find a way to do it, I'll amend my answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With