Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create Multiplatform Components in SwiftUI
Written by Team Kodeco

SwiftUI shines when it comes to creating UIs for different Apple platforms. With the same SwiftUI components, you can build interfaces that adapt natively to their environment, whether it’s an iPhone, iPad, Mac or even an Apple Watch or Apple TV. This section focuses on how to build components that seamlessly adapt across iOS and macOS.

As an example, let’s look at a simple SwiftUI view built with a TabView:

struct ContentView: View {
  var body: some View {
    TabView {
      Text("Tab 1")
        .tabItem {
          Label("Tab 1", systemImage: "1.circle")
        }
      
      Text("Tab 2")
        .tabItem {
          Label("Tab 2", systemImage: "2.circle")
        }
    }
  }
}

With an iPhone as your simulator, your preview should look like this:

A TabView with two tabs on an iPhone.
A TabView with two tabs on an iPhone.

Now change the simulator to My Mac and you’ll see the following:

A TabView with two tabs on a Mac.
A TabView with two tabs on a Mac.

In this example, you create a TabView with two tabs, each containing a Text view. On iOS, the TabView translates into a tab bar at the bottom of the screen. On macOS, it’s automatically adapted into tab controls at the top of the window, a more common pattern in many macOS applications. This platform-based adaptation applies to many other SwiftUI views, such as List, Button and so on.

Such adaptability is an advantage of SwiftUI that simplifies multiplatform development. You can write your UI code once and trust SwiftUI to adapt it appropriately for the target platform, creating a native and familiar experience for the user.

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.