Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a macOS App with SwiftUI
Written by Team Kodeco

Have you ever wanted to create a beautiful macOS app with SwiftUI? Look no further! SwiftUI allows developers to easily create stunning apps for macOS using declarative syntax. In this cookbook entry, we will show you how to create a basic macOS app using SwiftUI.

Begin by creating a new project in Xcode using the Multiplatform App template. Then, select your project at the top level of the project navigator, and click on the General tab. You’ll see Mac with its macOS SDK as one of the Supported Destinations.

Note: On Macs with Apple silicon, you’ll see Mac (Designed for iPad) as a default supported destination if you started with an iOS App template. This lets you run your existing iOS app on the Mac. There’s a third option too, Mac Catalyst, for porting iPad apps written with UIKit to the Mac.

Here’s what Xcode should look like starting from the Multiplatform App template:

Supported destinations in Xcode.
Supported destinations in Xcode.

Replace the existing ContentView struct in ContentView.swift with the following code:

struct ContentView: View {
  var body: some View {
    VStack {
      Text("Hello, SwiftUI on macOS!")
        .padding()
        .font(.title)
      Image(systemName: "applelogo")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 100, height: 100)
        .padding()
    }
  }
}

Here’s what your preview should look like after setting the destination to My Mac:

Preview of the macOS app.
Preview of the macOS app.

Let’s break down what’s happening in the code. You first create a new View called ContentView, which contains a VStack that vertically stacks the Text view and Image view. The Text view displays a friendly greeting, and the Image view displays the Apple logo. You then apply some visual styling using the padding and font modifiers. The .aspectRatio(contentMode: .fit) view modifier ensures the Apple logo fits within the frame without appearing oddly squashed or stretched.

Set the run destination to MacMy Mac, then build and run and you should now see a beautiful macOS app with a greeting and an Apple logo!

macOS app with a greeting and an Apple logo.
macOS app with a greeting and an Apple logo.

In just a few lines of code, you have created a basic macOS app using SwiftUI. With SwiftUI, developers can easily create beautiful multiplatform apps with a consistent user interface. Happy coding!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.