Build for macOS Big Sur

Build for macOS Big Sur

Platform conditions and sidebar layout for macOS Big Sur app

The sidebar looks good on iOS, to ensure that it'd also work well on macOS, we'll need Big Sur. In this section, we'll configure the app in such a way that it works just as well in macOS. This will be done by adding platform conditions. This allows one to show, hide or cusotmize elements based on the OS.

Downloads

To follow this course, you can download the source file, which will help you compare your progress.

Getting Started

To test whether or not what we've built so far would work for the Mac app, we'll need Big Sur. Let's start by switching from iOS to macOS. Make sure to select MyMac.
swiftui-section5-1

Conditionals

After switching, you'll notice some errors showing up. Let's fix these!
  • Add in an if statement as follows:

#if os(iOS)
List(0 ..< 20) {item in
CourseRow()
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("Courses")
#else
content
#endif
  • To be able to use the condition, add the following at the top
@ViewBuilder
var body: some View {
// Condition
}
swiftui-section5-2

Mini Components

Since, we'd like to avoid repeating code in the condition, we'll be using mini components. To create one, do the following:
  • Right after body, copy the list, delete it from body and paste it in content as follows:

@ViewBuilder
var body: some View {
// Condition
}
var content: some View {
// List
.listStyle(InsetGroupedListStyle())
.navigationTitle("Courses")
}
  • Then, add in content to the condition like below
#if os(iOS)
content
#else
content
#endif
  • Since, we only want the listStyle to be applied to iOS, remove it from content and place it in the if condition
#if os(iOS)
content
.listStyle(InsetGroupedListStyle())
swiftui-section5-3

Mac App

Resume the preview to take a look at how it looks. If you'd like to interact with the Mac app, click play and then, Bring Forward. Two windows open up, the first one is the preview and the second one is the app.
swiftui-section5-4

Frame

Here, we'll set a minimum size for the content to make it unable to go smaller than that size. In the else block, below content, add in:
.frame(minWidth: 800, minHeight: 600)
swiftui-section5-5

Sidebar

Let's also set a minimum size for the sidebar.
  • Head to Sidebar.swift. Here, we'll create a mini component in the same manner we did before

@ViewBuilder
var body: some View {
//remove the list and paste it in content
}
var content: some View {
// List
.listStyle(SidebarListStyle())
}
  • Next, let's add in the condition
#if os(iOS)
content
.navigationTitle("Learn")
#else
content
.frame(minWidth: 200, idealWidth: 250, maxWidth: 300)
#endif
swiftui-section5-6