Edmond is an iOS developer and currently works at Snowball. GitHub, blog, Twitter, Twitter

WWDC 2020 Session 10041 – What’s new in SwiftUI

Contents of this article

SwiftUI, launched in WWDC 2019, is arguably the most talked about technology for iOS development, building great user interfaces across all Apple platforms. This year we have SwiftUI 2.0, so let me take a look at some of the new features.

There are a lot of new features this year, more than we can cover in one talk, but we’ll try to cover as much as we can. We’ll also cover sessions, so you can check them out for more information.

Apps and Widgets

Let’s start with Apps and Widgets.

This is the first time Apple has used SwiftUI alone to build an entire app, rather than embedding SwiftUI code into UIKit, AppKit or WatchKit apps.

Let’s write a simple Hello World! Applications.

You read that right, this is a 100% working application.

App & Scene

SwiftUI packs a lot of intelligent, automatic and customizable behavior into a simple and flexible declarative API.

Let’s start with an application that tracks the progress of a book you’re reading.

At the bottom, you have a custom view to represent the main user interface of your application, while at the top you use that view as the content of your application’s main window.

The first thing to notice is the similarity between these two statements. We all define a protocol compliant structure.

We designed SwiftUI’s new App API to follow the declarative, state-driven pattern that you’re used to in view code. App ProtoCl allows us to easily replace AppDelegate and SceneDelegate with a structure that will manage our scene and application lifecycle.

Another key point is the return type of the body attribute. The Scene returned here is also a new concept in SwiftUI, indicating that the interface can be displayed independently by different platforms.

WindowGroup

WindowGroup is one of the specific applications of Scence and is a powerful example of how Scene provides off-the-shelf intelligent, multi-platform functionality in SwiftUI.

In our iOS application, WindowGroup is creating and managing a single full-screen window for our application. The same code runs on watchOS and manages a single full-screen window.

Although the two applications look different, the core applications on both platforms have the same structure, so they can share an application declaration.

In fact, my app also works on tvOS and iPad.

Because iPadOS supports multi-window applications, we got some additional features for free; Like being able to create multiple instances of an application that can be displayed side by side.

This also extends to macOS, which also supports multiple Windows. We can use the standard Command-n shortcut to create new Windows and collect them into a single tabbed window. SwiftUI even automatically adds the “New Window” menu command to my main menu.

SwiftUI also supports other types of scenarios that can be combined together like views to build more complex applications.

Like the new Settings scene on macOS, the Preferences window is easy to add.

Setting the scene automatically sets the standard Preferences command in the application menu and provides the correct styling for the window.

DocumentGroup

SwiftUI’s Scene API also supports document-based applications, such as the one we built for drawing vector shapes.

DocumentGroup scenes, which automatically manages the opening, editing and saving of document-based scenes supported by iOS, iPadOS and macOS.

On iOS and iPadOS, DocumentGroup will automatically display the document browser if no other home interface is provided.

On the Mac, DocumentGroup opens a different window for each new document and automatically adds commands to the main menu to perform common document actions.

Speaking of menu commands, SwiftUI allows you to add additional commands using the new.Commands modifier.

For example, here we add a custom shapes menu for adding new shapes to the canvas. MacOS will automatically add custom menus in the correct area of the main menu and display their keyboard shortcuts. These shortcuts were assigned using the new.keyboardShortcut view modifier.

The.Commands API provides much more functionality than we show here, such as the ability to locate commands based on user focus, and so on.

Xcode Support

To help you build these new apps, we’ve also added a new Multiplatform template specifically for SwiftUI apps, updated with new project experiences in Xcode.

These new templates are optimized for multi-platform code and can automatically be used for shared code as well as platform-specific components and resources.

The other part is how to configure the LaunchScreen for your application.

A new “LaunchScreen” key in infp.plist allows you to declare various combinations of LaunchScreen components. Examples include the default image, background color, and white space at the top and bottom (as configured in the image above).

If a Storyboard is already in use in an existing project, it will still work without replacement. However, for the new SwiftUI project, the LaunchScreen configuration is an easy choice.

SwiftUI App Sessions

We have prepared presentations on SwiftUI Apps to give a more in-depth look at what scenarios are and how they relate to applications and views:

  • App Essentials in SwiftUI – Explains how views, scenarios and applications work together in greater depth.
  • Build Document-based Apps in SwiftUI – Will take an in-depth look at how to open and manage documents in applications.

Widgets

Now let’s talk briefly about Widgets, one of the new offerings on iOS, iPadOS and macOS. Widgets can only be built using SwiftUI. It directly increases the importance of Swift and SwiftUI by a significant amount.

We can build widgets like Apps and Views using custom structures that conform to Widget Protocol.

There are many types of widgets we can make, such as this one that periodically recommends new albums to me.

Widgets can also be configured with other types of data, such as Siri Intents.

There’s a lot to discuss about building widgets, and we have some lectures to help you get started:

  • Design great widgets
  • Meet WidgetKit
  • What’s new in SwiftUI
  • Widgets Code-along, part 1: The adventure begins
  • Widgets Code-along, part 2: Alternate timelines
  • Widgets Code-along, part 3: Advancing timelines

It is recommended to watch Build SwiftUI Views for Widgets first for more information.

Widgets in watchOS

We can now use SwiftUI to build complex customizations for the Apple Watch. You can build full-color features like the coffee of the Week chart I created.

For building complex Watch apps, see Sessions:

  • Build complications in SwiftUI
  • Create complications for Apple Watch

Lists and Collections

Next, let’s talk about improvements to Lists and Collections. Lists are an important part of many applications and often represent the primary interface with which users interact. Lists gets some great new features in this release.

Outlines

Using Outlines, we simply declare dynamic and data-driven content to complete the presentation of general lists.

You can also provide a.chldren KeyPath at initialization to enable a nested display of the list.

By default, Lists are displayed using the system standard style on macOS, iOS and iPadOS.

We hope that ease-of-use Outlines can help and reduce the abuse of push-pop navigation mode by content-biased applications.

Grids

SwiftUI was most criticized last year for its unfriendly support for lists and grids. When we have hundreds or thousands of Views in Grids or Stacks, SwiftUI will directly initialize and create them, which is a very 😱 thing.

Fortunately, SwiftUI added lazy-loading to the grid layout this year, which can be combined with ScrollViews for smooth scrolling of grid content.

The grid has powerful layout capabilities and supports a variety of configurations, such as adjusting the column count to fit the available space, as we see here in landscape and portrait.

Or force a fixed number of columns, each of which can have its own resizing parameters, as in the example below, where no column is fixed to 4 columns.

Of course, SwiftUI also supports horizontal scrolling grids. In addition, we provide lazy-loading versions of VStack and HStack, which are great for building custom scrollable layouts.

For example, this image shows a waterfall flow:

We use LazyVStack as a container, and take advantage of the new Switch control feature in ViewBuilder to easily support various layouts of images. For example, a single large picture at the top, an asymmetric combination of multiple small size pictures in the middle, etc. These components work together to create a seamless picture stream.

In this article, we have only briefly covered some of the features. There are more new views, such as ScrollViewReader, TextEditor, and so on. For more on the power of SwfitUI’s Lists and Grids, check out Stacks, Grids, and Outlines in SwiftUI.

Toolbars and Controls

Now, let’s jump to SwiftUI’s support for Toolbars and the new way to customize controls.

Toolbar

From the beautiful look of macOS Big Sur to the updated iPad OS experience to primary Actions on watchOS. This year, we can construct all of these apis using SwiftUI’s new.toolbar modifier:

// Toolbar
BookList()
	.toolbar { / / # 1
		Button(action: .recordProgress) {
			Label("Record Progress", systemImage: "book.circle")}}BookList()
	.toolbar { // #2 is the same as #1
		ToolbarItem(placement: .primaryAction) {
         Button(action: recordProgress) {
				Label("Record Progress", systemImage: "book.circle")}}}BookList()
	.toolbar { / / # 3
		ToolbarItem(placement: .confirmationAction) { 
			Button("Save", action: saveProgress)
		}
      ToolbarItem(placement: .cancellationAction) {}
			Button("Cacnel", action: dismissSheet)
		}
	}
BooDetail()
	.toolbar { / / # 4
      ToolbarItem {
         Button(action: recordProgress) {
            Label("Progress", systemImage: "book.circle")}}ToolbarItem(placement: .bottomBar)
      	Button(action: .shareBook) {
				Label("Share", systemImage: "square.and.arrow.up")}}}Copy the code

The above code has the following effect:

The code above lists several ways to construct a toolbar. Toolbar Items are made up basically the same as the other views in SwiftUI, and in the above cases are all implemented by Button.

Another example is the use of principal semantics, which will be highlighted in the application, as we can see below:

The toolbar is placed in a familiar location by default or can be explicitly customized using the Toolbar.

We simply describe the status of these Toolbar items in SwiftUI, and SwiftUI automatically finds the correct location based on the semantic definition. For example, confirm and cancel operations in wathcOS are displayed at the top.

We can also specify placement for additional control, especially for relatively small screens. For example, in iOS, by specifying the.bottombar position of the shared item.

Label

In the example code above, you should have found a new use for the Label view in SwiftUI:

Label {
	Text("Progress")
} icon: {
	Image(systemName: "book.circle")}Copy the code

Label can now be a combination of Text and Image. Not only can we use internationalized keys to configure titles in different languages, but we can also use System Image and SF Symbol to set ICONS. To learn more about SF Symbol 2.0 visit session-10207.

For the previous toolbar example, the Label default only shows the icon on the button, while the text is used for auxiliary purposes. This behavior also applies to the Menu List.

Label List

Our Label supports display as a list. This article is perfectly aligned regardless of the icon size, and the Label works for dynamically typed fonts of different sizes. Take a look at this code:

List {
	Label("Intruduction to SwiftUI", 
         systemImage: "hand.wawve")
   Label("SwiftUI Essentials", 
         systemImage: "handstudentdesk")
   Label("Data Essentials to SwiftUI", 
         systemImage: "flowchart")}Copy the code

Label is displayed in a large layout by default. When you change to extraLarge, the icon and title are updated automatically, and it does a good job of rearranging text and adding list lines. Of course, accessibilityLarge, which can be larger, is also supported.

For larger fonts, the Label is updated to surround text to maximize the amount of visible text.

The comparison effect is as follows:

Help

Now, with label elements like toolbars that have a clean, icon-only style, it’s more important than ever to provide extra help for those elements.

With the new.help modifier, you can attach a description of the control’s role and display it as a tooltip on macOS.

Again, this modifier can be used on all platforms, because it also provides accessibility tips that can provide a better VoiceOver experience for your application anywhere.

New Views

ProgressView

SwiftUI now supports ProgressView, which not only supports linear style, but also brings circular style.

ProgressView("Downloading Photo", value: percentComplet)
	.progressViewStyle(CircularProgressViewStyle(tint: .blue))
Copy the code

Gauges

For watchOS 7+ it is now possible to get dashboard view in SwiftUI.

For Guage views, we can optionally set minimum and maximum values to control whether they are displayed.

New Effetct and Styling

Next, let’s take a look at creating some cool effects using SwiftUI.

HoverEffect

MacOS Big Sur rewrites the Notification Center and the new Control Center in the menu bar using SwiftUI, and the Control Center uses a SwiftUI action. It realizes smooth switching between different modules.

Next, we built a UI prototype to show the effect in action.

The collection of favorite albums is shown here, which consists of the album’s LazyGrid and selectdAlbumRow. Simply add matchedGeometryEffect for each button and attach the album ID and relative NameSpace. This way, when we choose our favorite album, it flows smoothly from the grid to the bottom of our favorite album line.

In addition to this preset effect, we can also configure custom animations through the provided API:

Styling

SwiftUI has also added a lot of convenient style modification features.

ContainerRelativeShape

As you can see from the widget on the album, the new ContainerRelativeShape will take a shape similar to the recently included memory to generate paths.

It effectively offsets the shape of the external container and automatically maintains concentricity with the shape of the content based on its offset.

There are other things that improve and enhance the experience of text elements.

Dynamic Type Scaling

Now in SwiftUI, images can be embedded as part of text and act as a unified collation in response to dynamic changes.

A new attribute wrapper, ScaledMetric, describes custom non-text metrics (such as layouts) that automatically scale based on the current base value.

// Dynamic Type Scaling
@ScaledMetric private var padding: CGFloat = 10.0
VStack {
	Text(albmu.nmae)
		.font(.custom("AvenirNext-Regular", size: 30))
		
	Text("\(Image(systemName: "music.mic")) \(album.artist)")
		.font(.custom("AvenirNext-Regular", size: 17))
}
.padding(padding)
.background(...)
Copy the code

The zoom effect is as follows:

In summary, this makes it easy to customize reactive layouts while still performing well. Of course, we can do more than this, even the system controls, can also be customized to their style.

Oh, right. Colors are also customizable.

List Item Tinting

Finally, a tineColor for list elements. Now we can easily configure different Tintingcolors for different items.

List {
	Section {
		Label("Menu", systemImage: "list.bullet")
		Label("Menu", systemImage: "heart")
			.listItemTine(.red)				
		Label("Menu", systemImage: "seal")
			.listItemTine(.purple)		
	}
	Section(header: Text("Recipes")) {... }
		.listItemTine(.monochrome)
}
Copy the code

Contrast effect:

System Integration

In the last section, let’s talk briefly about SwiftUI’s deep integration with the system.

Links to jump

URLs jump is now a first-class citizen of SwiftUI with the new Link View. It opens the link by default using a browser.

Also, Universal Link jumping between applications is supported. OpenURL can be used to access different applications.

Other features include Drag and Drop, Uniform Type Identifiers Frameworks, and Sign In With Apple, to name a few.

conclusion

It’s great to see how powerful and feature-rich the next iteration of SwiftUI is.

  • By providing more concise and easy-to-use protocols, such asAppSceneMaking it possible to build applications based on SwiftUI.
  • With the support of the new Widget API, SwfitUI has been elevated from a simple toy model to become part of a utility.
  • With new views, improved functionality and improved performance, SwiftUI will have the imagination to replace Storyboard directly and become a mainstay of visual programming in the near future 😂.

reading

  • App essentials in SwiftUI
  • Build complications in SwiftUI
  • Build document-based apps in SwiftUI
  • Build SwiftUI apps for tvOS
  • Build SwiftUI views for widgets
  • Data Essentials in SwiftUI
  • Introduction to SwiftUI
  • Stacks, Grids, and Outlines in SwiftUI

Limited welfare

This article is from WWDC20 Inside Reference. I recommend this column here.

The “WWDC Insider reference” series was initiated by the veteran Driver Weekly, Knowledge Collection and SwiftGG technology organizations. We’ve been doing it for a couple of years, and it’s been good. It is mainly for the annual WWDC content, do a selection, and call on a group of front-line Internet iOS developers, combined with their actual development experience, Apple documents and video content to do a second creation.

There are 213 sessions this year. WWDC20 Insider selected 135 of these sessions and produced 83 articles in just two weeks. It is on sale for a limited time, only 9.9 yuan, very special.

Read the article is not satisfied with the friends, pay close attention to subscribe to WWDC20 internal reference xiaozhuanlan.com/wwdc20 continue to read ~

Pay attention to our

We launched LSJCoiding, a weekly newsletter for veteran drivers, which is called a welcome update to each issue.