What’s New In SwiftUI 3.0?

SwiftUI helps you build great-looking apps across all Apple platforms with the power of Swift — and surprisingly little code. You can bring even better experiences to everyone, on any Apple device, using just one set of tools and APIs.

author

By Vinamra Singh

08 Nov, 2022

SwiftUI is Apple's declarative UI framework. It helps you build great apps across all Apple platforms with the power of Swift and minor code. At WWDC 2021, SwiftUI was updated with new enhancements and features. SwiftUI 3.0 is available on iOS 15, iPadOS 15, macOS 12 and watchOS 12.

There are various features added in SwiftUI 3.0, such as:

  • Markdown And New AttributedString API
  • Button Styles
  • AsyncImage For Loading Images
  • TextField Gets Better Keyboard Management
  • New onSubmit View Modifier And Deprecation of onCommit
  • SwiftUI Lists Are Now Searchable
  • Pull To Refresh
  • Navigation Support
  • Swift Charts
  • Lists Swipe Actions
  • A Task Modifier for Concurrency
  • New SwiftUI Material Struct
  • New Canvas and Timeline Views
  • Debugging Support
  • More Modifiers for Lists, Tabs, Alerts, and Sheets

Let's discuss the features mentioned above in detail!!!

Markdown And New AttributedString API

Markdown is a standard language for writing designed texts. You've probably seen much of it in GitHub Readme documentation. Beginning with iOS 15, Apple is bringing Markdown backing to the Foundation framework and SwiftUI.

  • In this way, you can add strings with Markdown syntax in SwiftUI Text, as shown below:
Text(**Connect** on [Twitter](url_here)!)
  • If you might want to redo a scope of characters in the series over, there's an all-new AttributeString API for SwiftUI and an improved NSAttributedString for UI Kit, as shown below
do {
    let thankYouString = try AttributedString(
        markdown:"**Welcome** to [website](https://example.com)")
} catch {
    print("Couldn't parse: \(error)")
}
  • You can modify it utilizing the new AttributeString and SwiftUIAttributes. And also, pass the AttributeString in SwiftyUI Text.

Button Styles

Button Styles

SwiftUI Buttons are more powerful now with new roles and styling modifiers. ButtonRole lets you describe the kind of button. Now have the ability to style SwiftUI Buttons. It accepts:-

  • Cancel

  • destructive

  • none

  • some()

  • Using the button style view modifier, you can apply BorderedButtonStyle, BorderlessButtonStyle, PlainButtonStyle, or DefaultButtonStyle.

  • For BorderedButtons, there's a new BorderedShape to describe whether you want it as a capsule, rounded rectangle, or automatic.

  • There are two more attributes:

    1. Control size: It chooses the button size from a few standard options.
    2. controlProminence: This defines opacity—no wonder the bottom-most buttons stand out.
  • Apple also exposed a CoreLocationUI button for SwiftUI known as [ LocationButton It provides a current standardized location UI and helps to fetch location coordinates quickly, as shown below:

LocationButton(.sendMyCurrentLocation) {
    // Fetch location with Core Location.
    }.labelStyle(.titleAndIcon)

AsyncImage For Loading Images

SwiftUI 3.0 brings AsyncImage to abstract the whole process. Previously, displaying remote URLs in images required setting up a loader and performing asynchronous tasks. Dealing with different loading states only added.

AsyncImage(url: URL(string: <url_here>)!)
  • AsyncImage lets you specify a transaction wherein you can pass an animation. Since It uses URLSession, it provides out-of-box support for caching.
  • You can also customize the output image by accessing the content argument. Furthermore, you can also use the placeholder argument to set a loading view.
  • You can also handle the different states of the result using the AsyncImagePhase enum from the content block, as shown below:
AsyncImage(url: URL(string: str)!, scale: 1.0){
  content in

  switch content{
  case .empty:
  case .success(let image):
  case .failure(let error):

TextField Gets Better Keyboard Management

In iOS 15, we have a new property wrapper, i.e., @FocusState, to programmatically manage the current active fields. It will be helpful in login and registration forms; we can now highlight a specific text field.

To implement programmatic focus on TextField in SwiftUI, we must bind FocusState in the focused state modifier. It does a boolean check to determine if the FocusState is attached to the same view. The submitLabel view modifier lets us set the keyboard return button with many other options.

New onSubmit View Modifier And Deprecation of onCommit

/

We have a new way of handling results. The onCommit callback for the return key is soft-deprecated, and there's an onSubmit view modifier. This modifier is meant to take text field results in a view hierarchy

Form{

    TextField("Email", text: $field1)
    SecureField("Password", text: $field2)
    TextField("Name", text: $field3)
        .submitScope(false) //setting true won't submit the values
  
  }
  .onSubmit {
      print(field1)
      print(field2)
      print(field3)
  }

You can optionally specify the view type using .onSubmit(of:). And later on, setting a submitScope to true ensures that the results of that hierarchy are not returned.

SwiftUI Lists Are Now Searchable

With iOS 15, Apple brings a searchable modifier to lists. To mark a list as searchable, you must wrap it inside a NavigationView. It lets you specify a bunch of search suggestions. Tapping on them will display the search completion text in the search bar.

SwiftUI lists with a search view as shown below:

struct Colors : Identifiable{
  var id = UUID()
  var name: String
}
struct SearchingLists: View {
      @State private var searchQuery: String = ""
      @State private var colors: [Colors] = [Colors(name: "Blue"),Colors(name: "Red"),Colors(name: "Green")]

      var body: some View {
          NavigationView {
              List($colors) { $color in
                  Text(color.name)
              }
              .searchable("Search color", text: $searchQuery, placement: .automatic){
                  Text("re").searchCompletion("red")
                  Text("b")
              }
              .navigationTitle("Colors List")
          }
      }
}

But, we need to consider a few things before proceeding, such as

The automatic placement will decide the search bar's location depending on the app's performance. We can now pass Binding arrays directly in Lists and get a Binding value for each row. A Binding value is required in SwiftUI TextField. We can use the onSubmit modifier or set up a computed property that filters in real-time. We can use search to track if the user interacts with the search view. It is also used to display/hide search results in an overlay or another perspective.

Pull To Refresh

Previously, pull to refresh was another missing feature. This forced us to use UIViewRepresentable workaroundsWith iOS 15, you can integrate it in a few lines of code with the refreshable modifier, as shown below:

var body: some View {
  NavigationView {
      List($colors){ $color in

          Text(color.name)
      }
      .refreshable {
          self.colors.append(Colors(name: "Newly added"))
      }
      .navigationTitle("Colors List")
  }
}
  • You can also fetch network requests, like async/await, within the refreshable modifier and display the results.

  • The native SwiftUI Pull to Refresh doesn't work on SwiftUI Grids or Scroll View. It does bring some customizability. There's the RefreshAction value to trigger a refresh manually.

Navigation Support

Now, there are two types of navigation support in SwiftUI 3.0.

Strongly-typed navigation

Navigation Stack supports push and pop navigation; you can have programmatic control over a navigation stack's state. Since the navigation path can be represented as a state, deep linking is now possible.

NavigationSplitView and Window

NavigationSplitView is a new way of dealing with multicolumn navigation. WindowGroup is now accompanied by Window , which declares a unique app window.

Swift Charts

Swift charts present sensible defaults for something like as shown below. It uses the SwiftUI syntax to make charts easy to read. It develops a blue graph using round numbers on the y-axis. SwiftUI views can also be used within a chart.

Chart(partyTasksRemaining) { task in 
    BarMark(
      x: .value("Date", task.date, unit: .day),
      y: .value("Tasks Remaining", task.remainingCount)
    )
} 

Lists Swipe Actions

  • Swipe to perform actions was another feature added in SwiftUI; with the new swipeActions modifier. It looks like this, as shown below, with the all-new Button style:
List {
    ForEach (colors, id:\.id){ color in
        Text(color.name)
            .swipeActions{
                Button(role: .destructive){
                    //do something
                }label: {
                    Label("Delete," systemImage: "xmark.bin")
                }

                Button{
                    //do something
                }label: {
                    Label("Pin", systemImage: "pin")
                }
            }
    }
}
  • Swipe actions will appear from the screen's trailing edge. However, we can configure them to work from the top side, as shown below:
.swipeActions(edge: .leading)
  • Swipe actions don't work with Binding Array Lists. By default, the first swipe action gets triggered on a full swipe. But you can change that by setting allowsFullSwipe to false.

A Task Modifier for Concurrency

Previously, when fetching data for views, many SwiftUI developers would resort to appear. With iOS 15, Apple brings an all-new task modifier to let your data load asynchronously. The ability to automatically cancel tasks when the attached SwiftUI view is destroyed makes the task modifier a convenient tool. Creating an endless scrolling list by loading more data on demand is a perfect use case for the task modifier. It'll also be handy for doing the heavy lifting of NavigationLink destination views.

New SwiftUI Material Struct

The Material struct blends foreground elements with the background by adding clarity and vibrancy to the views. It's an excellent alternative to visually blurring your SwiftUI ideas. The material type indicates the degree to which the background type passes the foreground element.

We use it as:

.background(.regularMaterial)
.background(.thinMaterial)
.background(.ultraThinMaterial)
.background(.thickMaterial)
.background(.ultraThicknMaterial)

New Canvas and Timeline Views

Canvas-Timeline Views

A drawRect in SwiftUI needed to be included earlier. But now, Apple is bringing it in the form of Canvas API and much more. This API supports drawing paths and shapes. So you can create rich graphics by setting masks and transforming and applying filters in your SwiftUI app.

  • But TimelineView takes it to another level by letting you wrap any SwiftUI views and set a schedule that can be periodic or configured at certain times through TimelineSchedule. TimelineViews are like widgets inside your app.

Debugging Support

Finally, SwiftUI now provides built-in support for debugging view hierarchy .

let _ = Self._printChanges()

Calling the function inside the view body would print the SwiftUI views modified on the last reload.

More Modifiers for Lists, Tabs, Alerts, and Sheets

SwiftUI List has gotten the most significant upgrades. If search view, refresh, and swipe actions weren't enough; there are many more ways to customize your lists, such as:

  • listRowSeparator and listSectionSeparator to show or hide separator lines.
  • listRowSeparatorTint and listSectionSeparatorTint to add a color tint to each row and section, respectively.
  • .insetStyle (alternatesRowBackgrounds:) for macOS.
  • Badges are set on the right-hand side of the SwiftUI List row. It is also available in SwiftUI TabViews with iOS 15.
  • SwiftUI Alert views are now deprecated. Instead, we've got new .alert modifiers .alert also brings a variant for error dialogs.
  • There's an interactiveDismissDisabled function where the developer can choose to prevent the dismissable of forms and sheets.

That's it! I hope you are still here! That's awesome!!! It means you are curious to know the latest updated features.

Now you know the latest updates that occur in SwiftUI 3.0 & how we implement them. But we hope to see further enhancements in how they assess and evaluate, and Quokka Labs will keep you informed of any updates as these progressions carry out.

Any queries, suggestions, or comments? Drop them in the comment section.

Thanks!!!

Tags

Swift 3.0

iOS app development

Similar blogs

Let’s Start a conversation!

Share your project ideas with us !

Talk to our subject expert for your project!

Feeling lost!! Book a slot and get answers to all your industry-relevant doubts

Subscribe QL Newsletter

Stay ahead of the curve on the latest industry news and trends by subscribing to our newsletter today. As a subscriber, you'll receive regular emails packed with valuable insights, expert opinions, and exclusive content from industry leaders.