Predefined SwiftUI code snippets in Xcode

Predefined SwiftUI code snippets in Xcode

Xcode includes predefined, top-level, SwiftUI code snippets which are not visible in the library (⇧⌘L).

Example of SwiftUI code snippet not available in Xcode library

Snippets are indicated with {} (curly brackets) in the autocompletion list.

Screen Shot 2022-06-20 at 3.23.52 PM.png

I was able to find the following snippets:

  1. ButtonStyle
  2. LabelStyle
  3. PreviewProvider
  4. Shape
  5. View
  6. ViewModifier

The snippets define placeholder tokens that can easily be substituted with the desired value during autocompletion.

Example of placeholder substitution

What follows is the default output for each snippet.

ButtonStyle

struct MyButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .background(.quaternary, in: Capsule())
            .opacity(configuration.isPressed ? 0.5 : 1)
    }
}

struct MyButtonStyle_Previews: PreviewProvider {
    static var previews: some View {
        Button(action: { print("Pressed") }) {
            Label("Press Me", systemImage: "star")
        }
        .buttonStyle(MyButtonStyle())
    }
}

LabelStyle

struct MyLabelStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        HStack {
            configuration.icon
                .frame(width: 50)
                .background(.quaternary, in: Circle())

            configuration.title

            Spacer()
        }
    }
}

struct MyLabelStyle_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            Label("Title 1", systemImage: "star")
            Label("Title 2", systemImage: "square")
            Label("Title 3", systemImage: "circle")
        }
        .labelStyle(MyLabelStyle())
    }
}

Preview Provider

struct MyPreviewProvider_Previews: PreviewProvider {
    static var previews: some View {
        Text("Hello, world!")
    }
}

Shape

struct MyShape: Shape {
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.addEllipse(in: rect)
        }
    }
}

struct MyShape_Previews: PreviewProvider {
    static var previews: some View {
        MyShape()
    }
}

View

struct: View {
    var body: some View {
      Hello, world!
    }
}

struct MyView_Previews: PreviewProvider {
    static var previews: some View {
        MyView()
    }
}

ViewModifier

struct MyModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(.quaternary, in: Capsule())
    }
}

struct MyModifier_Previews: PreviewProvider {
    static var previews: some View {
        Text("Hello, world!")
            .modifier(MyModifier())
    }
}

Did you find this article valuable?

Support Marco Eidinger by becoming a sponsor. Any amount is appreciated!