Contents

Creating your app’s interface with SwiftUI

Develop apps in SwiftUI with an interactive preview that keeps the code and layout in sync.

Overview

If you choose the SwiftUI framework to develop your app, you can see an interactive preview in the canvas as you lay out your user interface. Xcode keeps the changes you make to the source code, the user interface layout, and the canvas in sync. For example, when you edit views in the source editor, Xcode updates the corresponding views in the canvas.

If you create your project from the Multiplatform template or choose SwiftUI as the interface when you select another template, Xcode adds default preview macros to the SwiftUI code for you. Otherwise, you can generate a preview using coding intelligence or add preview macros yourself.

For more information about Xcode templates, see Creating an Xcode project for an app. For more details about adding previews, see Previewing your app’s interface in Xcode.

Display the SwiftUI preview

To show the preview, select a file that contains a preview macro in the Project navigator and, if necessary, choose Editor > Canvas to show the canvas. Then click the Resume button in the upper-right corner of the canvas to start the preview. Xcode builds and runs the code, displaying the results directly in the canvas.

[Image]

Use the controls at the bottom of the canvas to switch between different preview modes, add variants for appearances, select device settings such as orientation, and change the device.

Add views and modifiers using the library

You can add views and modifiers to your code from the library, and Xcode keeps the preview in sync with your changes.

To open the library, choose View > Show Library (press the Option key to open it as a window). Then click the Views or Modifiers button in the toolbar and drag user interface elements from the library to your source code. To find elements more quickly, begin entering the element’s name in the search field at the top of the Library.

[Image]

Edit user interface elements

Edit the user interface elements in your source code to see the changes in the preview. To highlight elements in the source code that appear in the preview, click the Selectable mode below the canvas and click the elements in the preview. Then go back to the default Live mode to test and interact with your views in the preview.

[Image]

Then use code completion, code intelligence, and the library of code snippets to help you write Swift and SwiftUI code. For more information, see Editing source files in Xcode and Writing code with intelligence in Xcode.

See Also

Essentials