Technology
6 min
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.
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:
Let's discuss the features mentioned above in detail!!!
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.
Text(**Connect** on [Twitter](url_here)!)
do {
let thankYouString = try AttributedString(
markdown:"**Welcome** to [website](https://example.com)")
} catch {
print("Couldn't parse: \(error)")
}
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:
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)
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(url: URL(string: str)!, scale: 1.0){
content in
switch content{
case .empty:
case .success(let image):
case .failure(let error):
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.
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.
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.
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 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 is a new way of dealing with multicolumn navigation. WindowGroup is now accompanied by Window , which declares a unique app window.
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)
)
}
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")
}
}
}
}
.swipeActions(edge: .leading)
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.
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)
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.
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.
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:
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!!!
Building a High-performance Ecommerce App with React Native
By Ayushi Shrivastava
5 min read
Personalisation in Mobile Apps: Boosting Engagement with AI
By Ayushi Shrivastava
5 min read
Developing iOS Apps for Wearables with watchOS & HealthKit
By Ayushi Shrivastava
5 min read
Mastering Cross-Platform Mobile App Development: Balancing Performance, UX, and Scalability in Multi-Environment Deployments
By Ayushi Shrivastava
5 min read
Technology
5 min
Building a high-performing e-commerce app? Learn how React Native transforming the future and delivers amazing results. Read this blog to build a successful React Native ecommerce app to improve the sales. Covering the features, step-by-by-step process, comparison with Flutter, etc. Give a read!
Technology
5 min
Personalization in mobile apps is the key driver to boost customer engagement. Read this blog to get insights of AI-driven techniques and real-world success stories to enhance your app's user experience and brand reputation.
Technology
5 min
Wearables and fitness trackers are transforming lifestyles, with the market expected to reach $41.3 billion. This blog explores developing iOS wearable apps using watchOS and HealthKit, covering interface design, HealthKit integration, testing, and compliance with Apple guidelines. Learn strategies to create seamless, user-centric apps for fitness, health monitoring, and productivity.
Feeling lost!! Book a slot and get answers to all your industry-relevant doubts