Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline TextField/TextEditor in SwiftUI for MacOS in forms

Tags:

macos

swiftui

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)
    }
}

enter image description here

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)
    }
}

enter image description here

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.

like image 520
G. Marc Avatar asked Oct 15 '25 15:10

G. Marc


1 Answers

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.

like image 139
JeremyP Avatar answered Oct 18 '25 10:10

JeremyP