macosswiftui

How to properly align a label in a SwiftUI form?


I've created a subclass of NSViewRepresentable to wrap an NSComboBox on macOS. Adding such a combo box to a Form is easy, but I can't find a way to put a label on the combo box that aligns as expected.

In the screenshot below the Repository label should be on the left side of the form, with the Owner and Workflow labels:

screenshot showing misaligned label

The code looks as follows, and I'm sure there must be a combination that somehow results in SwiftUI recognising the text as a label that should go on the left. But what?

        Form {
            TextField("Owner:", text: $owner.input, prompt: Text("user or organisation"))
            HStack {
                Label("Repository:", image:"")
                ComboBox(items: repositoryList.items.map({ $0.name }), text: $repository.input)`
            }
            Picker("Workflow:", selection: $workflowList.selected) {
                ForEach(workflowList.items) { w in
                    Text(w.name).tag(w)
                }
            }

Any ideas?


Solution

  • You are looking for LabeledContent.

    Form {
        // other controls...
        LabeledContent("Repository:") {
            ComboBox(items: repositoryList.items.map({ $0.name }), text: $repository.input)
        }
    }