跳转至
Protocol

GroupBoxStyle

This protocol is used to create a style for a GroupBox

Declaration

protocol GroupBoxStyle

Overview

By using GroupBoxStyle, the style can be used for a GroupBox across your application. To configure the current GroupBoxStyle for a view hierarchy, you only need to use the .groupBoxStyle() modifier.

The GroupBoxStyle protocol only requires that the user creates a makeBody(configuration:) function which accepts an instance of GroupBoxStyleConfiguration and returns a view. Here, we create a custom GroupBoxStyle called OrangeGroupBoxStyle. The custom style applies a variety of view modifiers to the content property of the configuration parameter to create a light orange GroupBox with some spacing between its label and content:

struct OrangeGroupBoxStyle: GroupBoxStyle {
    var background: some View {
        RoundedRectangle(cornerRadius: 5)
            .fill(Color.orange)
    }

    func makeBody(configuration: Configuration) -> some View {
        configuration.content
            .frame(maxWidth: 200, maxHeight: 30)
            .padding()
            .background(background)
            .opacity(0.4)
            .overlay(
                configuration.label
                    .padding(.leading, 4),
                alignment: .topLeading
            )
    }
}
We can then apply the custom style by initializing a GroupBox with init(label:content:) and passing our style to the groupBoxStyle(_:) view modifier:

struct ContentView: View {
    var label: some View {
        Label("Employee", systemImage: "person.fill")
            .foregroundColor(.red)
    }

    var body: some View {
        GroupBox(label: label) {
            Text("Aaron")
        }
        .groupBoxStyle(OrangeGroupBoxStyle())
    }
}
A screenshot displaying a light orange group box in the center of the screen which has a person icon in its upper left corner followed by the label "Employee." The content reads "Aaron" in light grey text owed to the lower opacity in the custom style.

See DefaultGroupBoxStyle for an example of a custom label applied with the default style.

Availability

iOS 14.0+

macOS 11.0+

Topics


Type Alias

Configuration The properties of a GroupBox instance being created.


Associated Type

Body A View representing the body of a GroupBox.


Instance Method

makeBody(configuration:) Creates a View representing the body of a GroupBox.