Skip to content

andreasley/CustomFormStyle

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CustomFormStyle

SwiftUI's Form can be styled with the modifier .formStyle(). macOS 15 brought official support for SwiftUI container iteration, making the construction of a custom FormStyle finally possible 1.

This sample creates a basic form style that's similar to the integrated GroupedFormStyle but more optimized for forms with many fields and more complex controls.

This sample only supports macOS, but adapting it for iOS would be easy.

import SwiftUI
import CustomFormStyle

struct ContentView: View
{
    var body: some View {
        Form {
            Section("Introduction") {
                Text("Hello! This form is using a custom `FormStyle` that looks similar to `GroupedFormStyle`, but provides some additional features.")
            }
            TextField("Name", text: .constant(""))
            LabeledContent("Some labeled content") {
                Text("Some text")
            }
            Toggle("This is neat", isOn: .constant(true))
            GroupBox("Some GroupBox") {
                TextField("Pet name", text: .constant(""))
                TextField("Favorite song", text: .constant(""))
            }
            Section("Additional Details") {
                Picker("Country", selection: .constant("Switzerland")) {
                    Text("Switzerland")
                }
            }
        }
        .formStyle(CustomFormStyle())
    }
}

Compared to GroupedFormStyle:

  • Uses full width for content
  • Label column is limited in width
  • Field column is left-aligned
  • Text fields have default style (not borderless)
  • Ability to specify if all fields should be indented (regardless if they have a label)

Notable issues, related to the extraction of labels from instances of TextField:

  • Using private APIs and Mirror, so probably not accepted into the App Store
  • Concurrency workarounds to use TextFieldStyle on MainActor
  • The title label will remain visible inside the text field (in addition to the label column)

Hopefully, macOS 16 or 17 will properly support a custom TextFieldStyle.

Footnotes

  1. If you need a custom FormStyle in macOS 14, you can use _VariadicView_MultiViewRoot instead of container iteration. More about that here.

About

A custom `FormStyle` for SwiftUI Form on macOS

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages