I need a SwiftUI multiline text input control for MacOS satisfying the following requirements:
- allow cursor control like in a editor (i.e. pressing RETURN causes a new line)
- working label in a form
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.