[VIP] DesignCode: Build SwiftUI apps for iOS 17

Create multiple apps for iOS 17 and visionOS using SwiftUI 5 and Xcode 15. In this course, we’ll be exploring the fresh and exciting features of SwiftUI 5! As we craft a variety of iOS apps from the ground up, we'll delve deep into the treasure trove that is SwiftUI's user interface, interactions, and animations. This adventure is perfect for you if you're just starting out or if you have a passion for tackling intriguing UI challenges.

Jun 24, 2024 - 02:25
Jun 24, 2024 - 02:24
 0  43
[VIP] DesignCode: Build SwiftUI apps for iOS 17

This Course

In this course, we’ll be exploring the fresh and exciting features of SwiftUI 5! As we craft a variety of iOS apps from the ground up, we'll delve deep into the treasure trove that is SwiftUI's user interface, interactions, and animations. This adventure is perfect for you if you're just starting out or if you have a passion for tackling intriguing UI challenges. 

  

Sonoma 3@1-3008x16922

  

Requirements

Get ready to dive into SwiftUI, your friendly neighborhood framework that's delightfully simple to pick up! With heaps of learning materials from both Apple and the incredible dev community, you're in good hands. And guess what? My approach is like a cozy chat over coffee, brimming with visuals, and we'll unravel the coding mystery together, one step at a time, all from a designer's point of view. Even if you're just starting, that's totally okay!

Just a heads up, though – being comfy with a computer and having dabbled a bit with HTML and CSS could come in handy. And to create an app for iOS 17, you'll need a Mac running on Sonoma or later, plus the trusty Xcode. So, let's jump right in and begin this exciting SwiftUI journey together!

  

Learning Path

We suggest making this course your trusty sidekick, pairing it up with the handy SwiftUI handbook and our other awesome SwiftUI courses. As you get more cozy with SwiftUI and Swift, feel free to level up and venture into our more advanced courses. Here's a little roadmap to guide your learning journey.

  

Beginners

  

Intermediate / Advanced

  

What’s new in Xcode 15

  

Sonoma 3@1-3008x16923

  

Get ready to meet your new best friend – Xcode 15. Picture yourself developing, testing, and sending off your apps to all Apple platforms, and doing it faster than ever before. Imagine a space where your code completes itself, your designs come to life through interactive previews, and your animations play out in real-time.

  

ENHANCED CODE COMPLETION

The code completion in Xcode 15 is now smarter, providing better top suggestions, resulting in safer and faster code writing. For example, when calling a function that has default arguments, Xcode provides all possible permutations of default arguments to help you pick the one you want.

  

SWIFT MACROS

One of the standout features of Xcode 15 is Swift Macros. This new language feature allows for more expressive APIs and helps eliminate repeated code. Macros can be expanded right in line with the help from quick actions, enabling you to even set a breakpoint on the code inside a macro if necessary.

  

SWIFT SYMBOLS FOR ASSET CATALOGS

Asset catalogs now use Swift symbols, meaning your color and image assets can now be code completed. This offers the benefit of type safety, eliminating the risk of missing colors or images at runtime.

  

Untitled

  

NEW ASSISTANT FOR DOCUMENTATION

In the spirit of enhancing code readability and maintainability, Xcode 15 introduces a new assistant for documentation. This real-time preview assistant allows you to see exactly how your documentation will look in a fully built documentation archive.

  

THE BOOKMARKS NAVIGATOR

As your project grows in complexity, the new bookmarks navigator in Xcode 15 keeps track of your progress. By creating bookmarks, you can easily mark places in your code you want to revisit or tasks you need to complete.

  

INTERACTIVE PREVIEWS

Previews in Xcode have been expanded to include UIKit and AppKit. Using macros, the new Previews API simplifies adding previews, giving you quick visual feedback for your UIViewControllers, SwiftUI Views, and widgets.

  

Untitled-2

  

Interactive Timeline: This new feature helps in the development and design of widgets, providing a more dynamic and interactive user interface design experience.

#Preview(as: .systemSmall) {
    CaffeineTrackerWidget()
} timeline: {
    CaffeineLogEntry.log1
    CaffeineLogEntry.log2
    CaffeineLogEntry.log3
    CaffeineLogEntry.log4
}

  

XCODE CLOUD

Xcode 15 introduces the option to deploy your apps seamlessly to TestFlight and the App Store from Xcode Cloud, further simplifying the app distribution process.

  

What's New in SwiftUI

Think of SwiftUI as your favorite graphics software blended with the power of Swift, and sprinkled with some React magic. It empowers you to whip up mind-blowing apps for all Apple devices with just a pinch of code and a whole lot of creativity.

SwiftUI translates your artistic visions directly into a functional and beautiful user interface. It's like painting with code—every stroke is a seamless blend of design and functionality. Imagine your app's interface elements as pieces of an interactive puzzle, coming together to form a complete picture of your unique vision.

  

ADVANCED ANIMATION CONTROL

Take control of animation like never before. With expanded support, you can now construct intricate animations using phases or keyframes. SwiftUI automatically transfers user gesture velocities into your animations, ensuring your app resonates with the fluidity and intuitiveness of natural movement.

  

ANIMATED SF SYMBOLS

HStack {
    Image(systemName: "rectangle.inset.filled.and.person.filled")
        .symbolEffect(.pulse)
    Image(systemName: "wifi")
        .symbolEffect(.variableColor.iterative.reversing)
    Image(systemName: "bubble.left.and.bubble.right.fill")
        .symbolEffect(.scale.down, isActive: isActive)
}

Untitled-3

  

SCROLL TRANSITIONS

Scroll transition modifier lets you apply effects to items in your scroll view, enhancing the visual appearance as they enter or leave the visible area.

CardView(card: card)
    .scrollTransition { content, phase in
        content
            .rotation3D(.degrees(phase.isIdentity ? 0 : 60), axis: (x: -1, y: 1, z: 0), perspective: 0.5)
            .rotationEffect(.degrees(phase.isIdentity ? 0 : -30))
            .offset(x: phase.isIdentity ? 0 : -200)
            .blur(radius: phase.isIdentity ? 0 : 10)
            .scaleEffect(phase.isIdentity ? 1 : 0.8)
    }

Untitled-4

  

KEYFRAME ANIMATOR

Keyframe Animator API allows for the animation of multiple properties in parallel, making it ideal for creating dynamic animations for apps.

KeyframeAnimator(
    initialValue: AnimationValues(), trigger: runPlan
) { values in
    LogoField(color: color)
        .scaleEffect(values.scale)
        .rotationEffect(values.rotation, anchor: .bottom)
        .offset(y: values.verticalTranslation)
        .frame(width: 240, height: 240)
} keyframes: { _ in
    KeyframeTrack(\.verticalTranslation) {
        SpringKeyframe(30, duration: 0.25, spring: .smooth)
        CubicKeyframe(-120, duration: 0.3)
        CubicKeyframe(-120, duration: 0.5)
        CubicKeyframe(10, duration: 0.3)
        SpringKeyframe(0, spring: .bouncy)
    }

    KeyframeTrack(\.scale) {
        SpringKeyframe(0.98, duration: 0.25, spring: .smooth)
        SpringKeyframe(1.2, duration: 0.5, spring: .smooth)
        SpringKeyframe(1.0, spring: .bouncy)
    }

    KeyframeTrack(\.rotation) {
        LinearKeyframe(Angle(degrees:0), duration: 0.45)
        CubicKeyframe(Angle(degrees: 0), duration: 0.1)
        CubicKeyframe(Angle(degrees: -15), duration: 0.1)
        CubicKeyframe(Angle(degrees: 15), duration: 0.1)
        CubicKeyframe(Angle(degrees: -15), duration: 0.1)
        SpringKeyframe(Angle(degrees: 0), spring: .bouncy)
    }
}

  

PHASE ANIMATOR

Phase Animator, simpler than Keyframe Animator, is used to animate sequences of phases, such as the rotation and scale of an icon.

  • New spring animations offer snappy or bouncy animations that can be used anywhere in SwiftUI animation.
  • Spring animations, with their natural feel and realistic friction, are now the default animation for apps built on iOS 17 and later versions.
  • The new sensory feedback API enables haptic feedback, which provides a tactile response for reinforcing actions and events.
  • The sensoryFeedback modifier supports haptic feedback across all platforms that can handle it.
HappyDog()
    .phaseAnimator(
        SightingPhases.allCases, trigger: sightingCount
    ) { content, phase in
        content
            .rotationEffect(phase.rotation)
            .scaleEffect(phase.scale)
    } animation: { phase in
        switch phase {
        case .shrink: .snappy(duration: 0.1)
        case .spin: .bouncy
        case .grow: .spring(
            duration: 0.2, bounce: 0.1, blendDuration: 0.1)
        case .reset: .linear(duration: 0.0)
        }
    }
    .sensoryFeedback(.increase, trigger: sightingCount)

  

VISUAL EFFECTS

  • Visual effects modifier allows updating elements based on their position without using a GeometryReader.
  • Visual effects can be used to create dynamic effects, like focusing on elements based on a focal point.
Circle()
    .fill(.red)
    .frame(width: 10, height: 10)
    .visualEffect { content, proxy in
        content.offset(position(in: proxy))
    }
DogImage(dog: dog)
    .visualEffect { content, geometry in
        content
            .scaleEffect(contentScale(in: geometry))
            .saturation(contentSaturation(in: geometry))
            .opacity(contentOpacity(in: geometry))
    }

  

METAL SHADER

SwiftUI's new ShaderLibrary allows for the transformation of Metal shader functions into SwiftUI shape styles.

ShaderLibrary.angledFill(
    .float(stripeSpacing),
    .float(stripeAngle),
    .color(.blue)
)

  

SIMPLIFIED DATA FLOW

SwiftUI now incorporates @Observable for a smooth and efficient data flow. It auto-detects the fields accessed by your views, optimizing rendering by redrawing only when necessary.

@Observable
class Dog: Identifiable {
    var id = UUID()
    var name = ""
    var age = 1
    var breed = DogBreed.mutt
    var owner: Person? = nil
}

class Person: Identifiable {
    var id = UUID()
    var name = ""
}

enum DogBreed {
    case mutt
}

  

SWIFTDATA

Starting with SwiftData is now a breeze in SwiftUI – it only takes a single line of code. Data modeled with @Model is automatically observed by SwiftUI, and @Query efficiently fetches, filters, and sorts data for your views, refreshing in response to changes.

import Foundation
import SwiftUI
import SwiftData

@main
private struct WhatsNew2023: App {

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(for: Dog.self)
    }

    struct ContentView: View {
        var body: some View {
            Color.clear
        }
    }

    @Model
    class Dog {
        var name = ""
        var age = 1
    }
}

  

BUILDING SPATIAL APPS

  

apps selection d5oucgbrc5me large 2x

  

Get ready to immerse your users in a three-dimensional world. By recompiling your SwiftUI apps for visionOS, you can add depth and 3D objects to windows or present volumes. Utilize RealityView to integrate RealityKit content with your views and controls, creating fully immersive experiences with SwiftUI and RealityKit.

  

INTERACTIVE WIDGETS

SwiftUI empowers you to design interactive widgets using Button and Toggle. Position your widgets in new locations like StandBy on iPhone, the Lock Screen on iPad, or the desktop on Mac, and let SwiftUI adapt your widget’s color and spacing to match the context across platforms.

  

INSPECTOR

The new feature, Inspector, is a modifier for displaying selection or context details in a distinct section in the app interface.

DogTagEditor()
.inspector(isPresented: $inspectorPresented) {
    DogTagInspector()
}

  

NEW MAPKIT APIS

Take the reins of the MapKit camera, annotations, map modes, and more. You can even place MapKit views within your widgets for an extra layer of user engagement.

struct Maps_Snippet: View {
    private let location = CLLocationCoordinate2D(
        latitude: CLLocationDegrees(floatLiteral: 37.3353),
        longitude: CLLocationDegrees(floatLiteral: -122.0097))

    var body: some View {
        Map {
            Marker("Pond", coordinate: location)
            UserAnnotation()
        }
        .mapControls {
            MapUserLocationButton()
            MapCompass()
        }
    }
}

  

NEW CHART TYPES AND INTERACTIVITY

Make data visualization more engaging by introducing pie and donut charts. Enable your users to delve into data with selection bands and scrolling.

Chart(sales, id: \.name) { element in
    SectorMark(
        angle: .value("Sales", element.sales),
        innerRadius: .ratio(0.6),
        angularInset: 1.5)
    .cornerRadius(5)
    .foregroundStyle(by: .value("Name", element.name))
}

  

Untitled-5

  

EXPANDED API COVERAGE

SwiftUI's API library keeps growing, now offering programmatic scrolling and paging, animated scroll transitions, a new Inspector component, fine-grained focus control, new keyboard input support, and more.

SwiftUI brings forth the future of coding, today. Welcome to a new paradigm of app development – simpler, faster, and more powerful than ever. SwiftUI is not just a framework, it’s your canvas to create the extraordinary. The future starts here. Your code awaits.

  

Download SF Fonts

If you're designing for iOS, it is essential to download the SF Fonts from Apple. There are 4 fonts:

  • SF Pro is the main font that is consistent across Apple's platforms, specifically for iOS, iPadOS and tvOS.
  • SF Compact is for watchOS design, optimized to be readable at smaller sizes.
  • SF Mono (optional) for evenly-spaced characters, which is useful for showing code.
  • New York is a serif typeface, typically for more traditional designs such as Books and News.

  

Figma Template

As I was building these apps, I followed the design that I made in Figma. From the Figma file, you'll be able to inspect the typography, sizes, colors and assets. Note that some screens in Xcode were built directly there.

Figma now has an iOS 17 UI Kit made officially by Apple.

  

Untitled-6

  

Midjourney App Icons

Midjourney is perfect for generating beautiful concepts and inspirations for your app icons. To fix visual inconsistencies, use Pixelmator’s repair tool or Photoshop’s content-aware fill and upscale the image to 2x. If you want to learn how to use Midjourney for design, we have a course.

  

App-20Icons

Beautiful square iOS icon. Concept store front. Flat render. Subtle gradients, no letters --v 4 --q 2

A square iphone app icon featuring top down perspective of a cafe interior. 3d. minimalistic. cute --q 2

Design a 1024×1024 square iOS app icon featuring a majestic camera, using a flat design style similar to the icons in the iOS 14 app store --q 2 --v 5.1

  

Multi-Platform App Icons

Once you decided on your app icon direction, adapt the concept for Beta, Mac and iOS. Follow their appropriate guidelines. For iOS, generate a 1024x1024 image in PNG for maximum quality.

  

DesignCode-20App-20Icons

  

Download Xcode 15 beta

To create our iOS 17 app, we'll use Xcode 15 beta. You can download it by registering a developer account and going to Downloads → Applications.

  

Create a New Xcode Project

  

Untitled-7

  

Once Xcode is installed, open the app and you'll see a welcome screen. Click on Create a New Xcode Project.

In this course, we'll focus on building for iOS. Select App inside the iOS tab, then click Next.

  

Time to fill the project details:

  • Product Name: this is the name of your app. E.G. News, Reminders, Mail. You don't need to include App at the end.
  • Team: this is useful if you wish to test on your device or publish to the App Store. If you have a developer account with Apple, you can set here, but otherwise you can do this later in Preferences under Accounts Tab with your Apple account. You can set None for now.
  • Bundle Identifier: this is your domain name in reverse. It's a unique ID for all your apps. E.G. com.twitter, com.instagram, com.figma.
  • Make sure to select SwiftUI as the interface and language to Swift.

  

Finally, click Next. Select a place to save your Xcode project, such as Downloads.

Congratulations, you've just created your Xcode Project! The first time you land, you'll see a fully open project with the project files on the left, the code editor in the middle with the Preview next to it and the Inspector in the right.

  

In Xcode, the Preview will automatically resume!

Make sure to have your a device selected in top bar. A good default is the iPhone 14.

  

Xcode Layout

Before we start, it is helpful to know your way around Xcode. These are the essential parts of working with SwiftUI inside Xcode 15.

  

Untitled-8

  

NAVIGATOR

The Navigator is where you'll navigate all the files, commits, issues for your project. By default, you'll have the Project Navigator tab selected. That's where you'll spend most of your time on, so it's important that you know how to get back to it, especially when Xcode sometimes auto-switches to other tabs when showing issues.

  

INSPECTOR

Whenever you have something selected in your code or assets, the inspector will give options based on that. The Attributes Inspector tab is the default and most relevant tab most of the time.

  

PREVIEW

By default, your preview will be interactive. The changes made in your code will be shown in real-time inside your Preview. You can also change to Selectable – the preview will be static and you can see the outlines of the selected elements in your code (Texts, Images, Stacks, etc).

  

PLAY IN SIMULATOR

In the top left, there is a giant Play button. This allows you to run your app on an iOS simulator which gives you all the extra options that the Preview won't give you, such as Home Apps, Save Screen, Slow Animations, Status Bar and a whole lot more.

  

KEYBOARD SHORTCUTS

  • Toggle Navigator (⌘ + 0): you can hide the Navigator to maximize your code editor.
  • Toggle Inspectors (⌘ + option + 0): the Inspectors are useful for editing your UI without writing code, but later on, you'll mostly do everything in code as it's faster and more efficient. That's why it's useful to hide the Inspectors when they're not needed.
  • Resume Preview ( ⌘ + option + P ): the Preview needs to be resumed at start, or when there is a more structural code change outside of your body UI. This shortcut will help save those precious seconds.
  • Run ( ⌘ + R ): run your app in the iOS Simulator. When running, you will have access to the logs, issues and performance graphs.
  • Stop ( ⌘ + . ): stop running the app. The app will remain in the Simulator, but you'll no longer get logs, issues, etc in real-time.
  • Build (⌘ + B): Xcode checks your code in real-time for errors and warnings. This prevents coding in the blind or tracing back too many steps. When the errors don't seem to disappear after a fix, a quick way to check if your code is fine is to Build.
  • Clean ( ⌘ + Shift + K ): a useful command when Xcode starts acting or doesn't seem to sync well with the changes you make. After a clean, it is recommended to Build again. If Xcode keeps acting, a good ol' Quit and Reopen can help, or as a last resort, a computer restart.
  • Library ( ⌘ + Shift + L ): a quick way to add views, modifiers, images and colours is to use the Library. It's also a great way to explore all UI elements and modifiers that are possible in SwiftUI.

  

Project Settings and Deployment Target

To go to Project Settings, click on the root item in the Navigator. The first thing you’ll want to change is the Display Name, which will show under your App Icon. This can differ from your Project Name.

  

Screenshot-202023-06-14-20at-205.00.03-E2-80-AFPM

  

Second, make sure that your deployment target is set to iOS 17. Otherwise, you'd need to create additional conditions that use the new iOS 17 features. This may be set by default eventually, but if it's not, you should change it.

  

Import Assets

To download the assets for this course, go to the bottom of any page and click the download link. Once you have downloaded the assets, go to the Assets section in the left Navigator and drag and drop the downloaded Assets folder into the Assets section of Xcode. If you want to learn how to import the App Icon, Color Sets, and Image assets manually, follow the optional steps provided.

  

Export App Icon

The first thing you want to set up is the App Icon. In Xcode 15, you only need a single image for your App Icon! Xcode will do all the scaling for you. In Figma, make sure to create an image that is 1024 x 1024 and export it to 1x in PNG. 

  

Screenshot-202023-06-14-20at-204.57.51-E2-80-AFPM

  

Import to Xcode

In Xcode, go to the Assets from the left Navigator. Select AppIcon and drag & drop the image that you exported.

  

Accent Color

Setting your custom colours in Xcode is the best way to set your colour styles for your design. It allows you to customize for Dark Mode and use HEX values. Starting with your Accent Color, set Appearances to Any, Dark. Then select each color and set content to sRGB or Display P3 and Input Method to 8-bit Hexadecimal. Now you can paste the HEX value from your design tool: #6234D5 for Any, #7443EF for Dark. 

  

Screenshot-202023-06-14-20at-204.57.08-E2-80-AFPM

  

Custom Color Sets

Right-click AccentColor and select New Color Set. Rename it to Background and set your desired colors: #F2F6FF for Any, #25254B for Dark. Select and click on New Folder from Selection. Rename to Colors. Here, you can add more colors.

  

Image Assets

For image assets, you can just drag and drop the folders from Finder to Xcode. By default, images will be set at 1x, scaling up as needed. You can also set images to be at 2x or 3x to make it easier to resize in code.

  

Using GPT-4

GPT-4 serves as a valuable resource for those embarking on the journey of learning SwiftUI and application development. It offers comprehensive responses to inquiries, provides step-by-step guidance, and adapts to individual learning paces. Here are some potentially beneficial prompts for enhancing your SwiftUI learning experience with GPT-4. For a deeper dive, we have a course on how to build apps with GPT-4.

  

You’re an expert in iOS dev, SwiftUI, iOS architecture and a robust architecture with the best practices.

- Provide steps to create a new project in Xcode.

  

GPT-4 won’t have knowledge of the new SwiftUI 5. To help, you can copy and paste from the documentation.

  

{paste documentation}

How to implement SwiftData from the documentation

  

Starting with your existing code can save you a lot of time when using ChatGPT. Provide your current code snippet to ChatGPT and ask it to create a sunflower pattern. Make sure to specify that everything should be kept in a single file for easier integration.

  

Update code: {paste entire code}

  

More resources to get started on SwiftUI

  

Untitled-9

  

  • You can watch SwiftUI WWDC videos using the Developer app from Apple. You can do a search on SwiftUI and watch the topics that interest you.
  • Download the Backyard Birds app to explore and learn how Apple made their sample app and some of the best practices for organizing your app. You can find more sample projects here.
  • SwiftUI by example by Paul Hudson is an excellent place to find short tutorials on key techniques for SwiftUI. Anytime you get errors or want to learn more about a topic, you'll want to do a Google search.
  • Our SwiftUI Handbook contains more than 130 tutorials with videos and sample code.
  • One of the best way to learn iOS design and design apps is to download the templates and libraries provided by Apple: https://developer.apple.com/design/resources/

  

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow