<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by alucchini on Medium]]></title>
        <description><![CDATA[Stories by alucchini on Medium]]></description>
        <link>https://medium.com/@ant.lucchini?source=rss-6e1c3421469------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m1q9_4uSlzS7AFV-Fx4pMA.jpeg</url>
            <title>Stories by alucchini on Medium</title>
            <link>https://medium.com/@ant.lucchini?source=rss-6e1c3421469------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:51:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ant.lucchini/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SwiftUI Conditional Modifiers: The Ultimate Guide to Cleaner Views]]></title>
            <link>https://medium.com/@ant.lucchini/swiftui-conditional-modifiers-the-ultimate-guide-to-cleaner-views-872ae0c447d9?source=rss-6e1c3421469------2</link>
            <guid isPermaLink="false">https://medium.com/p/872ae0c447d9</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ternary-operator]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[alucchini]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 15:00:57 GMT</pubDate>
            <atom:updated>2026-01-09T15:00:57.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_BWcY0vHYAC0n0AwxFVQw.png" /><figcaption>SwiftUI Conditional Modifiers illustration</figcaption></figure><h3>Stop fighting ternary operators and start writing declarative, readable SwiftUI code with these powerful View extensions.</h3><p>In the world of SwiftUI, we love the declarative syntax. It’s clean, it’s fast, and it’s intuitive. However, as soon as we need to apply modifiers <strong>conditionally</strong>, things can get messy. We often find ourselves trapped in a maze of ternary operators or wrapping views in clunky if-else blocks that break the natural flow of our code.</p><p><strong>In this article, you will learn how to:</strong></p><ul><li>Implement a clean .if() modifier to toggle styles.</li><li>Handle else cases gracefully within the same chain.</li><li>Safely unwrap optionals using a custom .ifLet() modifier.</li><li>Chain multiple modifiers together to keep your body property lightweight.</li></ul><h3>The Problem: The “Ternary” Headache</h3><p>Standard SwiftUI often forces us to write code like this:</p><pre>Text(&quot;Hello World&quot;)<br>    .padding()<br>    .background(isHighlighted ? Color.yellow : Color.clear)<br>    .opacity(isHighlighted ? 1.0 : 0.5)</pre><p>While this works for single properties, it becomes a nightmare when you want to apply a group of modifiers (like a shadow, a border, and a frame) only when a condition is met.</p><p>Let’s fix that with a robust <strong>View Extension</strong>.</p><h3>1. The Simple .if() Modifier</h3><p>The goal is to apply a transformation only if a condition is true. By using @ViewBuilder and Generics, we can create a modifier that feels like a native part of the framework.</p><pre>@ViewBuilder<br>func `if`&lt;TrueContent: View&gt;(<br>    _ condition: Bool,<br>    transform: (Self) -&gt; TrueContent<br>) -&gt; some View {<br>    if condition {<br>        transform(self)<br>    } else {<br>        self<br>    }<br>}</pre><h3>Why this is powerful:</h3><p>You can now group modifiers together inside the transform closure. Notice how we can chain 3 different modifiers inside a single if block:</p><pre>struct ProfileCard: View {<br>    @State var isPremium = true<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;User Profile&quot;)<br>        }<br>        .if(isPremium) { view in<br>            // Chaining 3 modifiers easily!<br>            view.padding()<br>                .background(Color.gold)<br>                .cornerRadius(10)<br>                .shadow(radius: 5)<br>        }<br>    }<br>}</pre><h3>2. Handling the “Else” Scenario</h3><p>Sometimes, you need to provide an alternative style when the condition is false. Instead of nesting more ternaries, we can overload our if function to handle an elseTransform.</p><pre>@ViewBuilder<br>func `if`&lt;TrueContent: View, FalseContent: View&gt;(<br>    _ condition: Bool,<br>    if ifTransform: (Self) -&gt; TrueContent,<br>    else elseTransform: (Self) -&gt; FalseContent<br>) -&gt; some View {<br>    if condition {<br>        ifTransform(self)<br>    } else {<br>        elseTransform(self)<br>    }<br>}</pre><h3>The Example: A Dynamic Follow Button</h3><p>Notice how we can chain multiple modifiers (padding, background, cornerRadius) inside both closures to create two completely different visual states.</p><pre>struct FollowButton: View {<br>    @State var isFollowing = false<br><br>    var body: some View {<br>        Button(isFollowing ? &quot;Unfollow&quot; : &quot;Follow&quot;) {<br>            isFollowing.toggle()<br>        }<br>        .if(isFollowing,<br>            if: { view in<br>                // Chained modifiers for the &#39;Following&#39; state<br>                view.padding(.horizontal, 20)<br>                    .padding(.vertical, 10)<br>                    .background(Color.gray.opacity(0.2))<br>                    .foregroundColor(.black)<br>                    .clipShape(Capsule())<br>            },<br>            else: { view in<br>                // Chained modifiers for the &#39;Not Following&#39; state<br>                view.padding(.horizontal, 20)<br>                    .padding(.vertical, 10)<br>                    .background(Color.blue)<br>                    .foregroundColor(.white)<br>                    .clipShape(Capsule())<br>                    .shadow(color: .blue.opacity(0.3), radius: 5, x: 0, y: 5)<br>            }<br>        )<br>    }<br>}</pre><h3>3. Mastering Optionals with .ifLet()</h3><p>One of the most frequent patterns in Swift is unwrapping optionals. In SwiftUI views, we often do this: if let user = user { Text(user.name) }.</p><p>But what if you want to apply a modifier <em>to an existing view</em> using an optional value? That’s where ifLet shines.</p><pre>@ViewBuilder<br>func ifLet&lt;Value, Content: View&gt;(<br>    _ value: Value?,<br>    transform: (Self, Value) -&gt; Content<br>) -&gt; some View {<br>    if let value = value {<br>        transform(self, value)<br>    } else {<br>        self<br>    }<br>}</pre><h3>Real-world Example:</h3><p>Imagine you have an optional “Promotion Label”. If it exists, you want to apply a specific background color and a tooltip:</p><pre>Circle()<br>    .frame(width: 50, height: 50)<br>    .ifLet(customColor) { view, color in<br>        view.foregroundColor(color)<br>            .overlay(Text(&quot;Special Offer!&quot;))<br>            .padding(5)<br>    }</pre><h3>4. The “If Let / Else” Pattern (Optional Handling)</h3><p>This is the “Holy Grail” of SwiftUI cleanliness. Often, if data is missing, you want to show a “placeholder” style or a disabled state. By adding an else transform to our ifLet, we handle both cases in one fluid chain.</p><pre>@ViewBuilder<br>func ifLet&lt;Value, TrueContent: View, FalseContent: View&gt;(<br>    _ value: Value?,<br>    if ifTransform: (Self, Value) -&gt; TrueContent,<br>    else elseTransform: (Self) -&gt; FalseContent<br>) -&gt; some View {<br>    if let value = value {<br>        ifTransform(self, value)<br>    } else {<br>        elseTransform(self)<br>    }<br>}</pre><h3>The Example: User Profile Header</h3><p>In this example, we apply a specific design if a premiumBadge exists, and a &quot;Standard&quot; design if it doesn&#39;t.</p><pre>struct UserHeader: View {<br>    let premiumBadge: String? // e.g., &quot;PRO&quot;<br><br>    var body: some View {<br>        Text(&quot;John Doe&quot;)<br>            .font(.headline)<br>            .ifLet(premiumBadge,<br>                if: { view, badgeText in<br>                    // If premium: add a badge, a gold border, and a shadow<br>                    view.overlay(<br>                        Text(badgeText)<br>                            .font(.caption2).bold()<br>                            .padding(4)<br>                            .background(Color.yellow)<br>                            .offset(x: 40, y: -10)<br>                    )<br>                    .padding()<br>                    .border(Color.yellow, width: 2)<br>                    .shadow(radius: 3)<br>                },<br>                else: { view in<br>                    // If standard: just add simple padding and a gray border<br>                    view.padding()<br>                        .border(Color.gray, width: 1)<br>                        .opacity(0.8)<br>                }<br>            )<br>    }<br>}</pre><h3>Why this is a game-changer for your workflow:</h3><ol><li><strong>Readability:</strong> Your view’s “main” definition remains at the top level, while conditional styling is neatly tucked into closures.</li><li><strong>Maintainability:</strong> You can easily add a third or fourth modifier to a specific state without touching the rest of the UI logic.</li><li><strong>No Type Erasure:</strong> Because we use @ViewBuilder and generics, SwiftUI keeps track of the underlying view types perfectly, ensuring smooth animations and transitions.</li></ol><h3>Key Performance Tip 💡</h3><blockquote><em>Using these extensions is generally safe, but remember that SwiftUI treats the </em><em>if and </em><em>else branches as different view identities. If you want a smooth transition between states, ensure you are using </em><em>.animation() appropriately!</em></blockquote><h3>Let’s Connect! 🚀</h3><p>I hope these extensions help you clean up your SwiftUI codebases as much as they helped mine. If you enjoyed this article and want to see more SwiftUI tips, iOS architecture deep-dives, or just want to chat about the latest in the Apple ecosystem, let’s connect on <a href="https://www.linkedin.com/in/antoine-lucchini-573178178/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=872ae0c447d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Soccer Ball Game in iOS with SwiftUI and SpriteKit: A Complete Tutorial]]></title>
            <link>https://medium.com/@ant.lucchini/building-a-soccer-ball-game-in-ios-with-swiftui-and-spritekit-a-complete-tutorial-737fc5d5e306?source=rss-6e1c3421469------2</link>
            <guid isPermaLink="false">https://medium.com/p/737fc5d5e306</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[spritekit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[alucchini]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 14:03:35 GMT</pubDate>
            <atom:updated>2025-12-28T14:03:35.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9Ozka5U2PssmVEjRWU7sQ.jpeg" /><figcaption>Soccer Ball, SwiftUI and SpriteKit Logos</figcaption></figure><h3>Introduction</h3><p>iOS game development often involves combining SwiftUI’s declarative UI with SpriteKit’s physics and 2D rendering. This walkthrough covers a simple soccer ball tapping game that uses both.</p><p>We’ll cover architecture, SpriteKit basics, physics setup, and how to integrate SpriteKit scenes into SwiftUI. Each code block is explained so you can adapt the approach to your own projects.</p><p>Don’t hesitate to connect with me on <a href="https://www.linkedin.com/in/antoine-lucchini-573178178/">LinkedIn</a> 😊.</p><h3>Project Overview</h3><p>The Soccer Ball App is a simple game where players tap the ball to keep it in the air. The goal is to achieve the highest score before the ball falls off the screen. It includes:</p><ul><li>Physics-based ball movement with gravity</li><li>Score tracking and personal best (persisted with UserDefaults)</li><li>Haptic feedback on tap</li><li>Game over state with restart</li><li>Clean separation between SwiftUI views and SpriteKit scenes</li></ul><p>The app uses SwiftUI for navigation and UI, and SpriteKit for the game scene and physics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QB3GfaYdjGCGJXCxEuS-yw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Df4GlQlXLczDHFz7zY21g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8rCj-qb6mFqinphd96zEQ.jpeg" /><figcaption>Soccer Ball Game screenshots</figcaption></figure><h3>What is SpriteKit?</h3><p>SpriteKit is Apple’s framework for 2D graphics, animations, and physics. It provides:</p><ul><li><strong>SKScene</strong>: The container for game content</li><li><strong>SKSpriteNode</strong>: Sprites (images/textures)</li><li><strong>SKPhysicsBody</strong>: Physics simulation (gravity, collisions, impulses)</li><li><strong>SKPhysicsWorld</strong>: Controls gravity and physics simulation</li><li><strong>SKLabelNode</strong>: Text labels</li></ul><p>Integrating SpriteKit with SwiftUI is done via SpriteView, which embeds an SKScene in a SwiftUI view.</p><h3>Architecture Breakdown</h3><p>The app has four main files:</p><ol><li><strong>SoccerBallAppApp.swift </strong>— App entry point</li><li><strong>HomeView.swift</strong> — Main navigation view</li><li><strong>ViewEnum.swift</strong> — View state enum</li><li><strong>SoccerView.swift</strong> — SpriteKit scene wrapper</li><li><strong>SoccerScene.swift</strong> — Core game logic and physics</li></ol><h3>Code Walkthrough</h3><h4>1. App Entry Point</h4><pre>import SwiftUI<br><br>@main<br>struct SoccerBallAppApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            HomeView()<br>        }<br>    }<br>}</pre><p>This is the app entry point. @main marks the entry, App defines the app structure, and WindowGroup sets HomeView as the root.</p><h4>2. View State Management</h4><pre>enum ActiveView {<br>    case home<br>    case soccer<br>}</pre><p>Simple enum to switch between the home screen and the game. This pattern keeps navigation clear and scalable.</p><h4>3. Home View with Navigation</h4><pre>struct HomeView: View {<br>    @State private var activeView: ActiveView = .home<br><br>    var body: some View {<br>        VStack {<br>            switch activeView {<br>            case .home:<br>                HStack {<br>                    Button {<br>                        activeView = .soccer<br>                    } label: {<br>                        VStack {<br>                            Image(&quot;soccer_ball&quot;)<br>                                .resizable()<br>                                .frame(width: 100, height: 100)<br>                            Text(&quot;Play&quot;)<br>                                .font(.title2)<br>                                .foregroundStyle(.black)<br>                        }<br>                    }<br>                }<br>                .padding(70)<br>            case .soccer:<br>                SoccerView()<br>            }<br>        }<br>        .frame(maxWidth: .infinity, maxHeight: .infinity)<br>        .background(.white)<br>    }<br>}</pre><ul><li><strong>@State</strong> tracks the current view</li><li>A <strong>switch</strong> renders either the home screen or the game</li><li>The home button updates state to navigate to the game</li><li><strong>.frame(maxWidth: .infinity, maxHeight: .infinity)</strong> fills the screen</li></ul><h4>4. SpriteKit Integration with SwiftUI</h4><pre>import SwiftUI<br>import SpriteKit<br><br>struct SoccerView: View {<br>    var scene: SKScene {<br>        let scene = SoccerScene()<br>        scene.size = CGSize(width: UIScreen.main.bounds.width, <br>                            height: UIScreen.main.bounds.height)<br>        scene.scaleMode = .resizeFill<br>        return scene<br>    }<br><br>    var body: some View {<br>        SpriteView(scene: scene)<br>            .edgesIgnoringSafeArea(.all)<br>    }<br>}</pre><ul><li><strong>SoccerView</strong> is a SwiftUI wrapper for the SpriteKit scene</li><li><strong>scene</strong> creates and configures the scene with screen size</li><li><strong>.scaleMode = .resizeFill</strong> makes the scene fill the available space</li><li><strong>SpriteView</strong> embeds the scene in SwiftUI</li><li><strong>.edgesIgnoringSafeArea(.all)</strong> extends to screen edges</li></ul><h4>5. Core Game Scene — Initialization</h4><pre>import SpriteKit<br>import GameplayKit<br>import UIKit<br><br>class SoccerScene: SKScene {<br>    private var ball: SKSpriteNode!<br>    private var scoreLabel: SKLabelNode!<br>    private var restartButton: SKLabelNode!<br>    private var personalBestLabel: SKLabelNode!<br>    <br>    private var score: Int = 0<br>    private let ballSize: CGFloat = 100.0<br>    private var personalBest: Int {<br>        get {<br>            return UserDefaults.standard.integer(forKey: &quot;personalBest&quot;)<br>        }<br>        set {<br>            UserDefaults.standard.set(newValue, forKey: &quot;personalBest&quot;)<br>        }<br>    }<br>    <br>    private let feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)</pre><ul><li><strong>SoccerScene</strong> inherits from <strong>SKScene</strong> (the game container)</li><li>Nodes are force-unwrapped optionals (created in <strong>didMove(to:)</strong>)</li><li><strong>personalBest</strong> is a computed property backed by UserDefaults</li><li><strong>UIImpactFeedbackGenerator</strong> provides haptic feedback</li></ul><h4>6. Scene Setup</h4><pre>override func didMove(to view: SKView) {<br>    self.size = view.bounds.size<br>    backgroundColor = .white<br>    <br>    setupBall()<br>    setupScoreLabel()<br>    setupPersonalBestLabel()<br>    setupRestartButton()<br>    <br>    physicsWorld.gravity = CGVector(dx: 0, dy: -4.8)<br>}</pre><ul><li><strong>didMove(to:)</strong> runs when the scene is presented</li><li>Scene size matches the view bounds</li><li>Physics gravity is set (negative Y pulls down)</li><li>Setup methods initialize nodes</li></ul><h4>7. Ball Setup with Physics</h4><pre>private func setupBall() {<br>    let texture = SKTexture(imageNamed: &quot;soccer_ball&quot;)<br>    ball = SKSpriteNode(texture: texture)<br>    ball.size = CGSize(width: ballSize, height: ballSize)<br>    ball.position = CGPoint(x: frame.midX, y: frame.midY)<br>    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2)<br>    ball.physicsBody?.restitution = 0.7<br>    ball.physicsBody?.linearDamping = 0.1<br>    ball.physicsBody?.allowsRotation = false<br>    ball.physicsBody?.velocity = .zero<br>    ball.physicsBody?.angularVelocity = 0<br>    addChild(ball)<br>}</pre><ul><li><strong>SKTexture</strong> loads the image asset</li><li><strong>SKSpriteNode</strong> creates the visual node</li><li><strong>SKPhysicsBody(circleOfRadius:)</strong> gives it a circular physics body</li><li><strong>restitution = 0.7</strong> sets bounce (0.0 = no bounce, 1.0 = full bounce)</li><li><strong>linearDamping = 0.1</strong> adds slight air resistance</li><li><strong>allowsRotation = false</strong> prevents spinning</li><li><strong>addChild(ball)</strong> adds it to the scene</li></ul><h4>8. UI Labels Setup</h4><pre>private func setupScoreLabel() {<br>    scoreLabel = SKLabelNode(text: &quot;Score: 0&quot;)<br>    scoreLabel.position = CGPoint(x: frame.midX, y: frame.maxY - 150)<br>    scoreLabel.fontSize = 24<br>    scoreLabel.fontColor = .black<br>    addChild(scoreLabel)<br>}<br><br>private func setupPersonalBestLabel() {<br>    personalBestLabel = SKLabelNode(text: &quot;Personal Best: \(personalBest)&quot;)<br>    personalBestLabel.position = CGPoint(x: frame.midX, y: frame.maxY - 200)<br>    personalBestLabel.fontSize = 16<br>    personalBestLabel.fontColor = .black<br>    addChild(personalBestLabel)<br>}</pre><ul><li><strong>SKLabelNode</strong> displays text</li><li>Positions use <strong>frame.midX</strong>, <strong>frame.maxY</strong> for layout</li><li><strong>addChild()</strong> adds them to the scene</li></ul><h4>9. Touch Handling and Game Mechanics</h4><pre>override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>    if let touch = touches.first {<br>        let location = touch.location(in: self)<br>        if restartButton.contains(location) &amp;&amp; !restartButton.isHidden {<br>            restartGame()<br>        } else if ball != nil &amp;&amp; ball.contains(location) {<br>            feedbackGenerator.impactOccurred()<br>            <br>            let offset = ball.position.x - location.x<br>            let impulseX = offset * 2<br>            let impulseY: CGFloat = 300<br>            <br>            ball.physicsBody?.applyImpulse(CGVector(dx: impulseX, dy: impulseY))<br>            <br>            score += 1<br>            scoreLabel.text = &quot;Score: \(score)&quot;<br>            <br>            if score &gt; personalBest {<br>                personalBest = score<br>                personalBestLabel.text = &quot;Personal Best: \(personalBest)&quot;<br>            }<br>        }<br>    }<br>}</pre><ul><li><strong>touchesBegan</strong> handles tap events</li><li>Touch location is in scene coordinates</li><li>Restart button is checked first</li><li>Triggers haptic feedback</li><li>Calculates horizontal offset for directional impulse</li><li>Applies upward impulse with horizontal component</li><li>Increments score and updates labels</li><li>Saves new personal best if needed</li></ul><h4>10. Game Loop and Boundaries</h4><pre>override func update(_ currentTime: TimeInterval) {<br>    if ball != nil &amp;&amp; ball.position.y + ball.size.height &lt; frame.minY {<br>        gameOver()<br>    }<br>    <br>    if ball != nil &amp;&amp; ball.position.x &lt; frame.minX {<br>        ball.position.x = frame.minX<br>        ball.physicsBody?.velocity.dx = -ball.physicsBody!.velocity.dx<br>    } else if ball != nil &amp;&amp; ball.position.x &gt; frame.maxX {<br>        ball.position.x = frame.maxX<br>        ball.physicsBody?.velocity.dx = -ball.physicsBody!.velocity.dx<br>    }<br>}</pre><ul><li><strong>update(_:)</strong> runs every frame</li><li>Game over when the ball falls below the screen</li><li>Side boundaries bounce the ball by reversing horizontal velocity</li></ul><h4>11. Game Over and Restart Logic</h4><pre>private func gameOver() {<br>    let gameOverLabel = SKLabelNode(text: &quot;Game Over&quot;)<br>    gameOverLabel.position = CGPoint(x: frame.midX, y: frame.midY)<br>    gameOverLabel.fontSize = 48<br>    gameOverLabel.fontColor = .red<br>    addChild(gameOverLabel)<br>    <br>    restartButton.isHidden = false<br>    isPaused = true<br>    ball.removeFromParent()<br>    ball = nil<br>}<br><br>private func restartGame() {<br>    score = 0<br>    scoreLabel.text = &quot;Score: \(score)&quot;<br>    setupBall()<br>    restartButton.isHidden = true<br>    <br>    children.filter { $0 is SKLabelNode &amp;&amp; ($0 as! SKLabelNode).text == &quot;Game Over&quot; }<br>        .forEach { $0.removeFromParent() }<br>    <br>    isPaused = false<br>}</pre><p><strong>gameOver():</strong></p><ul><li>Shows “Game Over” label</li><li>Shows restart button</li><li>Pauses the scene</li><li>Removes the ball</li></ul><p><strong>restartGame():</strong></p><ul><li>Resets score</li><li>Recreates the ball</li><li>Removes the game over label</li><li>Unpauses the scene</li></ul><h3>Key Takeaways</h3><p>This project shows:</p><ol><li>Integrating SpriteKit with SwiftUI using SpriteView</li><li>Setting up physics bodies and world gravity</li><li>Handling touch input for game interactions</li><li>Managing game state (playing, paused, game over)</li><li>Persisting data with UserDefaults</li><li>Adding haptic feedback for better UX</li></ol><p>The architecture separates concerns: SwiftUI handles navigation and UI, while SpriteKit handles game logic and rendering.</p><h3>Conclusion</h3><p>You can build engaging games by combining SwiftUI’s declarative UI with SpriteKit’s physics and rendering. This app demonstrates core concepts you can extend — collision detection, particle effects, animations, and more.</p><p>Experiment with physics parameters (gravity, restitution, damping), add obstacles, power-ups, or multiple levels. The foundation is flexible enough to grow into a more complex game.</p><p>The full source code is available on my <a href="https://github.com/alucchini/Soccer-Ball-Game/tree/main">GitHub repository</a>. Feel free to fork it, modify it, and make it your own!</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=737fc5d5e306" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Custom Calendar in SwiftUI]]></title>
            <link>https://medium.com/@ant.lucchini/how-to-build-a-custom-calendar-in-swiftui-34656aa33f3d?source=rss-6e1c3421469------2</link>
            <guid isPermaLink="false">https://medium.com/p/34656aa33f3d</guid>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[calendar]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[alucchini]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 14:53:33 GMT</pubDate>
            <atom:updated>2025-02-07T14:53:33.969Z</atom:updated>
            <content:encoded><![CDATA[<p>SwiftUI’s native DatePicker is powerful, but sometimes you need more control over design and functionality. In this article, we’ll build a fully customizable calendar component to select dates and times in a way that best fits your application’s User Experience (UX) and branding. Let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gK7DXkYV6h2F3XLI-osBoA.png" /><figcaption>Custom Calendar in SwiftUI</figcaption></figure><h3>Project Overview</h3><p>We’ll create a <strong>CustomCalendar</strong> project that showcases a calendar which allows users to:</p><ul><li>Navigate through months</li><li>Select a valid date (no past dates)</li><li>Pick an hour and minute (time selector)</li><li>Receive the combined date and time back in the parent view</li></ul><p>This custom approach enables you to style every component precisely as you desire.</p><h3>Prerequisites</h3><p>Before you begin, ensure you have:</p><ul><li>A Mac with Xcode installed (Xcode 14 or later is recommended).</li><li>Basic knowledge of <strong>Swift</strong> and <strong>SwiftUI</strong>.</li><li>A desire to customize default Apple components for a more personalized UI.</li></ul><h3>Core Components</h3><p>The main building blocks of this project are:</p><h4>1. <strong>ContentView</strong></h4><p>This is the entry point for the SwiftUI app. Here, we embed our ScheduleView, which in turn contains our custom calendar (CalendarView).</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    var body: some View {<br>        ScheduleView { date in<br>            print(&quot;Date selected: \(date)&quot;)<br>        }<br>        .padding()<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p><strong>Key Points:</strong></p><ul><li>We pass a closure to ScheduleView that prints the selected date (including hours).</li><li>This closure could be replaced by any custom logic you need, such as saving the date to a database or updating a label.</li></ul><h4>2. <strong>ScheduleView</strong></h4><p>ScheduleView manages the state of the selected date (selectedSessionDate) and time (selectedSessionHour), then combines them when the user taps the checkmark button.</p><pre>import SwiftUI<br><br>struct ScheduleView: View {<br>    @State private var selectedSessionDate: Date = Date.now<br>    @State private var selectedSessionHour: Date = Date.now<br>    <br>    var onDateSelected: (String) -&gt; Void<br>    <br>    var body: some View {<br>        VStack(spacing: 10) {<br>            VStack {<br>                Text(&quot;Custom Schedule View&quot;)<br>                    .font(.system(size: 20, weight: .semibold))<br>                    .foregroundStyle(.white)<br>                    .textCase(.uppercase)<br>            }<br>            <br>            CalendarView { selectedDate, selectedHour in<br>                self.selectedSessionDate = selectedDate<br>                self.selectedSessionHour = selectedHour<br>            }<br>            <br>            HStack {<br>                Spacer()<br>                Button {<br>                    let combinedDate = Calendar.current.date(<br>                        bySettingHour: selectedSessionHour.hourInt,<br>                        minute: selectedSessionHour.minuteInt,<br>                        second: 0,<br>                        of: selectedSessionDate<br>                    ) ?? selectedSessionDate<br>                    <br>                    onDateSelected(combinedDate.formattedDateHourCombined)<br>                } label: {<br>                    Image(systemName: &quot;checkmark&quot;)<br>                        .resizable()<br>                        .renderingMode(.template)<br>                        .frame(width: 20, height: 20)<br>                        .foregroundStyle(.blue)<br>                        .padding()<br>                        .background(<br>                            Circle()<br>                                .stroke(.blue, lineWidth: 2)<br>                                .fill(.blue.opacity(0.1))<br>                        )<br>                }<br>            }<br>            Spacer()<br>        }<br>    }<br>}</pre><p><strong>Key Points:</strong></p><ul><li>The user picks a date in CalendarView.</li><li>When the checkmark button is pressed, it merges the selected date and time into one Date.</li><li>It calls onDateSelected to report this back to the parent.</li></ul><h4>3. <strong>CalendarView</strong></h4><p>The CalendarView is where the main logic of our custom calendar resides. It displays a grid of days, handles month navigation, and integrates a time picker.</p><pre>import SwiftUI<br><br>struct CalendarView: View {<br>    @State private var currentMonth = Date.now<br>    @State private var selectedDate = Date.now<br>    @State private var selectedHour = Date.now<br>    @State private var days: [Date] = []<br>    <br>    let daysOfWeek = Date.capitalizedFirstLettersOfWeekdays<br>    let columns = Array(repeating: GridItem(.flexible()), count: 7)<br>    <br>    var onDateSelected: (Date, Date) -&gt; Void<br>    <br>    var body: some View {<br>        VStack(spacing: 20) {<br>            // Month navigation<br>            HStack {<br>                Text(currentMonth.formatted(.dateTime.year().month()))<br>                    .font(.system(size: 16, weight: .bold))<br>                    .foregroundStyle(.white)<br>                Spacer()<br>                Button {<br>                    currentMonth = Calendar.current.date(byAdding: .month, value: -1, to: currentMonth)!<br>                    updateDays()<br>                } label: {<br>                    Image(systemName: &quot;chevron.left&quot;)<br>                        .font(.title2)<br>                        .foregroundStyle(.blue)<br>                }<br>                Button {<br>                    currentMonth = Calendar.current.date(byAdding: .month, value: 1, to: currentMonth)!<br>                    updateDays()<br>                } label: {<br>                    Image(systemName: &quot;chevron.right&quot;)<br>                        .font(.title2)<br>                        .foregroundStyle(.blue)<br>                }<br>            }<br>            <br>            // Days of the week row<br>            HStack {<br>                ForEach(daysOfWeek.indices, id: \.self) { index in<br>                    Text(daysOfWeek[index])<br>                        .font(.system(size: 14, weight: .medium))<br>                        .foregroundStyle(.white)<br>                        .frame(maxWidth: .infinity)<br>                }<br>            }<br>            <br>            // Grid of days<br>            LazyVGrid(columns: columns, spacing: 10) {<br>                ForEach(days, id: \.self) { day in<br>                    Button {<br>                        if day &gt;= Date.now.startOfDay &amp;&amp; day.monthInt == currentMonth.monthInt {<br>                            selectedDate = day<br>                            onDateSelected(selectedDate, selectedHour)<br>                        }<br>                    } label: {<br>                        Text(day.formatted(.dateTime.day()))<br>                            .font(.system(size: 14, weight: .medium))<br>                            .foregroundStyle(foregroundStyle(for: day))<br>                            .frame(maxWidth: .infinity, minHeight: 40)<br>                            .background(<br>                                Circle()<br>                                    .foregroundStyle(<br>                                        day.formattedDate == selectedDate.formattedDate<br>                                            ? .blue<br>                                            : .clear<br>                                    )<br>                            )<br>                    }<br>                    .disabled(day &lt; Date.now.startOfDay || day.monthInt != currentMonth.monthInt)<br>                }<br>            }<br>            <br>            // Time picker<br>            DatePicker(<br>                &quot;&quot;,<br>                selection: $selectedHour,<br>                displayedComponents: [.hourAndMinute]<br>            )<br>            .onChange(of: selectedHour) {<br>                onDateSelected(selectedDate, selectedHour)<br>            }<br>            .datePickerStyle(.compact)<br>            .datePickerStyle(GraphicalDatePickerStyle())<br>            .colorMultiply(.white)<br>            .environment(\.colorScheme, .dark)<br>        }<br>        .padding()<br>        .onAppear {<br>            updateDays()<br>            onDateSelected(selectedDate, selectedHour)<br>        }<br>    }<br>    <br>    private func updateDays() {<br>        days = currentMonth.calendarDisplayDays<br>    }<br>    <br>    private func foregroundStyle(for day: Date) -&gt; Color {<br>        let isDifferentMonth = day.monthInt != currentMonth.monthInt<br>        let isSelectedDate = day.formattedDate == selectedDate.formattedDate<br>        let isPastDate = day &lt; Date.now.startOfDay<br>        <br>        if isDifferentMonth {<br>            return isSelectedDate ? .black : .white.opacity(0.3)<br>        } else if isPastDate {<br>            return .white.opacity(0.3)<br>        } else {<br>            return isSelectedDate ? .black : .white<br>        }<br>    }<br>}</pre><p><strong>Key Points:</strong></p><ul><li><strong>Month Navigation</strong>: We can increment or decrement the current month using Calendar.current.date(byAdding: .month, value:±1).</li><li><strong>Date Grid</strong>: A LazyVGrid displays the days. If a day belongs to the previous or next month, we style it differently (faded or disabled).</li><li><strong>Time Picker</strong>: A DatePicker is used for hour and minute selection. This is synced with our selected date and triggers a closure upon change.</li><li><strong>Styling</strong>: The foregroundStyle(for:) function handles coloring for selected days, past days, and days in the current month.</li></ul><h4>4. Date Extension (ExtDate.swift)</h4><p>The custom Date extension handles a wide range of calculations: from computing month boundaries to formatting. This helps keep CalendarView clean and readable.</p><pre>import Foundation<br><br>extension Date {<br>    static var firstDayOfWeek = Calendar.current.firstWeekday<br>    <br>    static var capitalizedFirstLettersOfWeekdays: [String] {<br>        let calendar = Calendar.current<br>        // Adjusted for the different weekday starts<br>        var weekdays = calendar.shortWeekdaySymbols<br>        if firstDayOfWeek &gt; 1 {<br>            for _ in 1..&lt;firstDayOfWeek {<br>                if let first = weekdays.first {<br>                    weekdays.append(first)<br>                    weekdays.removeFirst()<br>                }<br>            }<br>        }<br>        return weekdays.map { $0.capitalized }<br>    }<br>    <br>    var startOfMonth: Date {<br>        Calendar.current.dateInterval(of: .month, for: self)!.start<br>    }<br>    <br>    var endOfMonth: Date {<br>        let lastDay = Calendar.current.dateInterval(of: .month, for: self)!.end<br>        return Calendar.current.date(byAdding: .day, value: -1, to: lastDay)!<br>    }<br>    <br>    var numberOfDaysInMonth: Int {<br>        Calendar.current.component(.day, from: endOfMonth)<br>    }<br>    <br>    var firstWeekDayBeforeStart: Date {<br>       let startOfMonthWeekday = Calendar.current.component(.weekday, from: startOfMonth)<br>       var numberFromPreviousMonth = startOfMonthWeekday - Self.firstDayOfWeek<br>       if numberFromPreviousMonth &lt; 0 {<br>           numberFromPreviousMonth += 7 // Adjust to a 0-6 range if negative<br>       }<br>       return Calendar.current.date(byAdding: .day, value: -numberFromPreviousMonth, to: startOfMonth)!<br>    }<br>    <br>    var calendarDisplayDays: [Date] {<br>       var days: [Date] = []<br>       // Start with days from the previous month to fill the grid<br>       let firstDisplayDay = firstWeekDayBeforeStart<br>       var day = firstDisplayDay<br>       while day &lt; startOfMonth {<br>           days.append(day)<br>           day = Calendar.current.date(byAdding: .day, value: 1, to: day)!<br>       }<br>       // Add days of the current month<br>       for dayOffset in 0..&lt;numberOfDaysInMonth {<br>           if let newDay = Calendar.current.date(byAdding: .day, value: dayOffset, to: startOfMonth) {<br>               days.append(newDay)<br>           }<br>       }<br>       return days<br>    }<br>    <br>    var monthInt: Int {<br>        Calendar.current.component(.month, from: self)<br>    }<br>    <br>    var startOfDay: Date {<br>        Calendar.current.startOfDay(for: self)<br>    }<br>    <br>    var hourInt: Int {<br>        Calendar.current.component(.hour, from: self)<br>    }<br>    <br>    var minuteInt: Int {<br>        Calendar.current.component(.minute, from: self)<br>    }<br>    <br>    var formattedDate: String {<br>        let formatter = ISO8601DateFormatter()<br>        formatter.timeZone = .current<br>        formatter.formatOptions = [.withFullDate]<br>        return formatter.string(from: self)<br>    }<br>    <br>    var formattedDateHourCombined: String {<br>        let formatter = ISO8601DateFormatter()<br>        formatter.timeZone = .current<br>        return formatter.string(from: self)<br>    }<br>}</pre><p><strong>Key Points:</strong></p><ul><li><strong>Weekday Adjustments</strong>: Accounts for different locales and first weekday preferences.</li><li><strong>Month Calculations</strong>: startOfMonth, endOfMonth, and numberOfDaysInMonth simplify handling of monthly boundaries.</li><li><strong>Display Days</strong>: calendarDisplayDays merges the previous month’s trailing days, current month days, and potentially next month’s leading days in a single array.</li><li><strong>Date Formatting</strong>: formattedDate for day-month-year and formattedDateHourCombined for day, month, year, hour, and minute.</li></ul><h3>How It Works</h3><ol><li><strong>User Lands on </strong><strong>ContentView</strong><br>The app loads ScheduleView, which contains the main logic.</li><li><strong>Display Calendar &amp; Time Picker</strong><br>CalendarView calculates which days to display based on the current month, then allows the user to navigate backward or forward in time.</li><li><strong>Select a Date &amp; Hour</strong><br>Once a user taps on a day, selectedDate is updated. The time picker updates selectedHour.</li><li><strong>Confirm Selection</strong><br>Pressing the checkmark in ScheduleView merges selectedSessionDate with selectedSessionHour into a single Date, returning it to the parent via onDateSelected.</li></ol><p>This pattern gives complete control over how days, months, and time appear and behave, making it a breeze to implement custom designs and logic.</p><h3>Putting It All Together</h3><ol><li><strong>Create a new SwiftUI project</strong> in Xcode named <strong>CustomCalendar</strong> (or any name you prefer).</li><li><strong>Add the following files (</strong>ContentView.swift, ScheduleView.swift, CalendarView.swift, ExtDate.swift (for the Date extension))</li><li><strong>Run the project</strong> on the iOS Simulator. You’ll see a custom calendar, with weekday headers, month navigation, and a time picker.</li><li><strong>Style &amp; Refine</strong>: Adjust colors, fonts, and layout to suit your UI design requirements.</li></ol><h3>Conclusion</h3><p>A custom SwiftUI calendar can help you:</p><ul><li>Fully control the look and feel of date selection.</li><li>Incorporate advanced features (like disabling past dates or customizing the weekday start).</li><li>Integrate seamless transitions between dates, times, and parent views.</li></ul><p>With the code in this article, you have a strong foundation to tailor the experience any way you want. Whether you’re building a to-do app, a scheduling tool, or anything else requiring a date picker, a bespoke calendar can elevate both the user experience and your app’s overall design.</p><p><strong>Happy coding and customizing!</strong></p><blockquote><strong><em>Follow Me </em></strong><em><br>If you enjoyed this tutorial, feel free to follow me on </em><a href="https://www.linkedin.com/in/antoine-lucchini-573178178/"><em>LinkedIn</em></a><em> for more SwiftUI tips and updates. You can also find the complete source code on my </em><a href="https://github.com/alucchini/CustomCalendar"><em>GitHub</em></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34656aa33f3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Hex Color Made Easy: A Simple Extension for Your Projects]]></title>
            <link>https://medium.com/@ant.lucchini/swiftui-hex-color-made-easy-a-simple-extension-for-your-projects-189d200ec915?source=rss-6e1c3421469------2</link>
            <guid isPermaLink="false">https://medium.com/p/189d200ec915</guid>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[alucchini]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 09:30:32 GMT</pubDate>
            <atom:updated>2025-01-24T09:30:32.331Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to create and use a custom SwiftUI extension to work with hex color values. This step-by-step guide will streamline your design process, making color management more intuitive in iOS development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRRyb7ljACwxCzwY7D7d_w.jpeg" /></figure><h3>Introduction</h3><p>When developing iOS apps with SwiftUI, you often need to manage color schemes for consistent and appealing user interfaces. One of the most popular formats for defining colors is the hexadecimal (hex) representation, commonly used in web and design tools. However, SwiftUI’s built-in Color struct doesn’t directly provide a constructor that accepts hex strings.</p><p>In this article, we’ll show you how to simplify color handling by creating a custom extension to work with hex values. You’ll learn how to implement it, how it functions, and best practices for incorporating it into your apps.</p><h3>Why Use Hex Colors in SwiftUI?</h3><ul><li><strong>Consistency with Web and Design Tools:</strong> Designers frequently share color palettes in hex format, making it convenient to implement the same values directly in your SwiftUI code.</li><li><strong>Readability and Maintenance:</strong> Hex codes provide a concise way to write and identify colors, saving you from dealing with multiple values for red, green, and blue channels.</li><li><strong>Wider Community Adoption:</strong> Hex color definitions are widely recognized, so using them in your Swift code makes your projects more accessible for new collaborators.</li></ul><h3>Implementing a Custom Color Extension</h3><p>Below is the code you can use to initialize a Color in SwiftUI using a hex string. It accounts for the leading # character and converts your hex value into its corresponding RGB components.</p><pre>extension Color {<br>    init(hex: String) {<br>        let scanner = Scanner(string: hex)<br>        _ = scanner.scanString(&quot;#&quot;)<br><br>        var rgb: UInt64 = 0<br>        scanner.scanHexInt64(&amp;rgb)<br><br>        let red = Double((rgb &gt;&gt; 16) &amp; 0xFF) / 255.0<br>        let green = Double((rgb &gt;&gt; 8) &amp; 0xFF) / 255.0<br>        let blue = Double(rgb &amp; 0xFF) / 255.0<br><br>        self.init(red: red, green: green, blue: blue)<br>    }<br>}</pre><h3>How It Works</h3><ul><li><strong>Remove the ‘#’</strong>: The code checks for and ignores the leading # character if it exists.</li><li><strong>Convert to Hex</strong>: scanHexInt64(&amp;rgb) parses the remaining string into a UInt64 value.</li><li><strong>Extract RGB Values</strong>: Bitwise operations calculate separate red, green, and blue values.</li><li><strong>Normalize to SwiftUI’s </strong><strong>Color</strong>: Each component is divided by 255.0 to get the normalized color used by SwiftUI.</li></ul><h3>How to Use This Extension</h3><ul><li><strong>Add the Extension to Your Project</strong><br>Copy and paste the above extension into a .swift file in your SwiftUI project. You might call it Color+Extensions.swift for clarity.</li><li><strong>Initialize Your Color with a Hex String</strong></li></ul><pre>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;Hello, SwiftUI!&quot;)<br>            .foregroundColor(Color(hex: &quot;#FF6B6B&quot;))<br>            .padding()<br>    }<br>}</pre><p>This uses a bright red color defined by the hex #FF6B6B.</p><h3>Best Practices and Tips</h3><ul><li><strong>Validate Your Hex Strings</strong>: Ensure your hex string is properly formatted (e.g., #RRGGBB). Unhandled cases might cause the scanner to fail.</li><li><strong>Use Naming Conventions</strong>: You may store color hex strings in a centralized place (like a Constants file) for better maintainability.</li><li><strong>Fallback for Invalid Strings</strong>: Consider providing a default color or throwing an error if the hex string is invalid, to prevent runtime issues.</li><li><strong>Use SwiftUI Previews</strong>: Quickly test your new colors in Xcode’s SwiftUI preview to confirm that they match your intended designs.</li></ul><h3>Conclusion</h3><p>By extending SwiftUI’s Color struct to accept hex values, you streamline color management in your projects. This approach is especially beneficial if you frequently receive design files with hex codes or want to maintain a consistent design across platforms. With just a few lines of code, you can ensure your color palette is both clean and readable.</p><h4>Find Me on LinkedIn</h4><p>Connect with me on LinkedIn for more tips and insights: <a href="https://www.linkedin.com/in/antoine-lucchini-573178178/">Antoine Lucchini</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=189d200ec915" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Stunning Animated Background in SwiftUI with Metal]]></title>
            <link>https://medium.com/@ant.lucchini/create-a-stunning-animated-background-in-swiftui-with-metal-32164bda67d9?source=rss-6e1c3421469------2</link>
            <guid isPermaLink="false">https://medium.com/p/32164bda67d9</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[gradient]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[metal]]></category>
            <dc:creator><![CDATA[alucchini]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 14:20:23 GMT</pubDate>
            <atom:updated>2024-10-15T14:20:23.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3ZLCtmwzLER9Y0MKjJByg.png" /></figure><p>In this tutorial, I’ll walk you through building an animated gradient background using Metal and SwiftUI. This dynamic background adds a modern touch to your app, creating a smooth, grainy gradient that evolves over time. This is perfect for apps that need a visually appealing backdrop to stand out from the crowd. Let’s dive into the details!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*O_P_TGFg4ilosX3HSXWoSg.gif" /><figcaption>Animated Animation Video in Low Quality</figcaption></figure><p><strong>What You’ll Need</strong></p><ul><li>Xcode 15+</li><li>Swift 5.9+</li><li>Basic understanding of SwiftUI</li><li>Experience with Metal shaders is helpful but not required</li></ul><p><strong>What We’ll Build</strong></p><p>We’ll create a SwiftUI app that displays a dynamic background using a custom shader written in Metal. The gradient will transition smoothly using Hermite interpolation and a grainy effect for added texture.</p><p><strong>Step 1: Setting Up the SwiftUI Project</strong></p><p>To start, create a new SwiftUI project in Xcode. Name it <strong>AnimatedBackground</strong>. Here’s the structure of our app:</p><pre>import SwiftUI<br><br>@main<br>struct AnimatedBackgroundApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>}</pre><p>In this example, the ContentView will house our animated background logic. We use TimelineView to continuously update the gradient based on time.</p><p><strong>Step 2: Building the ContentView</strong></p><p>The ContentView is where the magic happens. We use TimelineView with .animation to create a smooth update loop for our gradient.</p><pre>struct ContentView: View {<br>    @State private var startTime = Date.now<br><br>    var body: some View {<br>        TimelineView(.animation) { timeline in<br>            let elapsedTime = startTime.distance(to: Date.now)<br>            Rectangle()<br>                .frame(maxWidth: .infinity, maxHeight: .infinity)<br>                .foregroundStyle(.grainGradient(time: elapsedTime * 3))<br>                .opacity(0.6)<br>                .background(.black)<br>                .ignoresSafeArea()<br>        }<br>    }<br>}</pre><p>The TimelineView drives the animation, recalculating the gradient over time. This allows the gradient to change smoothly.</p><p><strong>Step 3: Gradient Color Configuration</strong></p><p>We define a set of colors that will form our gradient. For flexibility, we create an extension to initialize Color from a hex string.</p><pre>extension Color {<br>    init(hex: String) {<br>        let scanner = Scanner(string: hex)<br>        _ = scanner.scanString(&quot;#&quot;)<br>        var rgb: UInt64 = 0<br>        scanner.scanHexInt64(&amp;rgb)<br>        <br>        let red = Double((rgb &gt;&gt; 16) &amp; 0xFF) / 255.0<br>        let green = Double((rgb &gt;&gt; 8) &amp; 0xFF) / 255.0<br>        let blue = Double(rgb &amp; 0xFF) / 255.0<br>        <br>        self.init(red: red, green: green, blue: blue)<br>    }<br>}</pre><p>We then define gradient colors:</p><pre>private let tl = Color(hex: &quot;#41FF00&quot;)<br>private let tc = Color(hex: &quot;#FF97E8&quot;)<br>private let tr = Color(hex: &quot;#FFF200&quot;)<br><br>private let ml = Color(hex: &quot;#FF97E8&quot;)<br>private let mc = Color(hex: &quot;#FFF200&quot;)<br>private let mr = Color(hex: &quot;#41FF00&quot;)<br><br>private let bl = Color(hex: &quot;#FFF200&quot;)<br>private let bc = Color(hex: &quot;#41FF00&quot;)<br>private let br = Color(hex: &quot;#FF97E8&quot;)</pre><p>These colors will be used to create a gradient that smoothly blends over time.</p><p><strong>Step 4: Metal Shader for the Grainy Gradient</strong></p><p>Now comes the fun part: using Metal to create a smooth, animated gradient with a grainy texture. Here is the Metal shader code:</p><pre>#include &lt;metal_stdlib&gt;<br>#include &lt;SwiftUI/SwiftUI.h&gt;<br><br>using namespace metal;<br><br>float h00(float x) { return 2.0 * x * x * x - 3.0 * x * x + 1.0; }<br>float h10(float x) { return x * x * x - 2.0 * x * x + x; }<br>float h01(float x) { return 3.0 * x * x - 2.0 * x * x * x; }<br>float h11(float x) { return x * x * x - x * x; }<br><br>float hermite(float p0, float p1, float m0, float m1, float x) {<br>    return p0 * h00(x) + m0 * h10(x) + p1 * h01(x) + m1 * h11(x);<br>}</pre><p>This function performs Hermite interpolation, allowing smooth transitions between colors. We use sine waves to adjust color positions over time, creating a dynamic effect.</p><p><strong>Step 5: Interpolation &amp; Grain Effect</strong></p><p>The Metal shader uses interpolation to create a smooth transition between colors. It calculates the grainy effect by introducing randomness based on the position and time:</p><pre>half4 grainGradient(float2 position, float4 bounds, float size, float time, device const half4 *colors, int count) {<br>    const int2 gridSize = int2(size);<br>    const int4 gridRange = int4(0, 0, gridSize.x - 1, gridSize.y - 1);<br>    const int gridLastIndex = count - 1;<br><br>    float2 coords = position / bounds.zw;<br>    half4 result = gridInterpolation(coords, colors, float4(gridRange), gridSize, gridLastIndex, time * 0.20);<br><br>    float strength = 16.0;<br>    float x = (coords.x + 4.0 ) * (coords.y + 4.0 ) * 10.0;<br>    float4 grain = float4(fmod((fmod(x, 13.0) + 1.0) * (fmod(x, 123.0) + 1.0), 0.01)-0.005) * strength;<br><br>    result = result + half4(grain);<br>    return result;<br>}</pre><p>This code adds a subtle noise to the gradient, giving it a textured appearance. Adjusting the strength value changes the intensity of the grain.</p><p><strong>Step 6: Putting It All Together</strong></p><p>Finally, connect the shader with SwiftUI using a custom extension:</p><pre>extension ShapeStyle where Self == AnyShapeStyle {<br>    static func grainGradient(time: TimeInterval, gridSize: Int = 3) -&gt; Self {<br>        return AnyShapeStyle(ShaderLibrary.default.grainGradient(<br>            .boundingRect,<br>            .float(3),<br>            .float(time),<br>            .colorArray([tl, tc, tr,<br>                         ml, mc, mr,<br>                         bl, bc, br])<br>        ))<br>    }<br>}</pre><p>This function enables us to use .grainGradient directly in SwiftUI views, creating a visually stunning effect.</p><p><strong>Wrapping Up</strong></p><p>With this setup, you’ve created a beautiful, animated background using SwiftUI and Metal. The combination of Hermite interpolation and grain effects gives the gradient a unique and eye-catching look. Feel free to experiment with colors, timing, and grain intensity to create the perfect background for your app.</p><p><strong>Final Thoughts</strong></p><p>Integrating Metal shaders with SwiftUI can seem challenging at first, but it unlocks powerful possibilities for animations and visuals. If you enjoyed this tutorial, don’t forget to share your creations in the comments!</p><p>[<a href="https://github.com/alucchini/AnimatedBackgroundMetal">Github</a>] — [<a href="https://www.linkedin.com/in/antoine-lucchini-573178178/">Linkedin</a>] — [<a href="https://antoinelucchini.fr/">Portfolio</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32164bda67d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Document Scanner App with SwiftUI and SwiftData]]></title>
            <link>https://medium.com/@ant.lucchini/building-a-document-scanner-app-with-swiftui-and-swiftdata-2b47b76b57a4?source=rss-6e1c3421469------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b47b76b57a4</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[scanner-app]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[alucchini]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 09:59:51 GMT</pubDate>
            <atom:updated>2024-10-01T09:59:51.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFVks6mHRHTmckHpofYElQ.png" /></figure><h3><strong>Introduction</strong></h3><p>In today’s digital age, the ability to scan documents on the go is invaluable. In this tutorial, we will walk you through the creation of a <strong>document scanning app</strong> named <strong>Scanner Pro</strong> using <strong>SwiftUI</strong> and <strong>SwiftData</strong>. This app allows users to scan, view, rename, print, and share documents seamlessly.</p><h4>The app features:</h4><ul><li>Document scanning using the camera</li><li>Preview of scanned pages</li><li>Renaming and sharing functionalities</li><li>PDF generation for easy printing</li><li>Saving with SwiftData</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpNinfbVNGLXCFXjQJvRuA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmOlfZHErE6M2YBqD5d93g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSyJSqFpXn0VVo_Xpe-1Xg.png" /></figure><h3><strong>What is SwiftData?</strong></h3><p>SwiftData is a powerful and expressive persistence framework built for Swift. We’ll show you how you can model your data directly from Swift code, use SwiftData to work with your models, and integrate with SwiftUI. (<a href="https://developer.apple.com/videos/play/wwdc2023/10187/#:~:text=SwiftData%20is%20a%20powerful%20framework,create%20a%20seamless%20API%20experience.">Apple Doc</a>)</p><h3><strong>Setting Up the Project</strong></h3><p>Let’s dive into the implementation of <strong>Scanner Pro</strong> step by step. First, make sure you have Xcode installed on your macOS system and create a new SwiftUI project.</p><p>1. Open Xcode and select “Create a new Xcode project”.</p><p>2. Choose “App” under the iOS tab and click “Next”.</p><p>3. Name your project ScannerPro, select Swift as the language, and SwiftUI for the interface.</p><h3>First Step : SwiftData Model</h3><p>SwiftData and SwiftUI perform best when tightly integrated, and when you separate them — when you want to introduce view models into your code — you lose a fair amount of their power. However, with some extra work MVVM can be used just fine with SwiftUI and SwiftData, as long as you’re careful to keep your data synchronized.</p><p><strong>Tip:</strong> If you used Core Data previously you’ll know that <strong>NSFetchedResultsController</strong> allowed us to execute a query and monitor it for changes. We don&#39;t have an equivalent in SwiftData, so you need to keep your data model updated by hand.</p><p>Regardless of whether you use MVVM or not, your underlying SwiftData models are the same. For this project, we’ll use this simple <strong>Document</strong> model:</p><pre>import Foundation<br>import SwiftData<br>import UIKit<br><br>@Model<br>final class Document {<br>    var name: String<br>    var images: [ImageData] // Array of ImageData objects<br>    var date: Date<br><br>    init(name: String, images: [ImageData], date: Date) {<br>        self.name = name<br>        self.images = images<br>        self.date = date<br>    }<br><br>    var preview: UIImage? {<br>        return images.first?.image // Accesses the first image&#39;s UIImage representation<br>    }<br>}<br><br>@Model<br>final class ImageData {<br>    var imageData: Data // Stores the image as raw data<br><br>    init(imageData: Data) {<br>        self.imageData = imageData<br>    }<br><br>    var image: UIImage? {<br>        return UIImage(data: imageData) // Converts Data back to UIImage<br>    }<br>}</pre><p>In SwiftData, you cannot directly use images as attributes in a model due to the way data persistence is designed. Here’s a breakdown of why this is the case and how the ImageData class provides a solution:</p><p><strong>1. Data Storage Limitations</strong></p><ul><li>SwiftData is designed to efficiently manage and store data types that can be serialized and persisted. Directly storing images (like UIImage) isn’t feasible because they are complex objects that consume a significant amount of memory and can’t be directly serialized into a format suitable for databases.</li></ul><p><strong>2. Data Representation</strong></p><ul><li>Instead of storing the image itself, we store its raw data (in the form of Data). The ImageData class serves as a wrapper that converts the Data back into a UIImage when needed. This separation allows for more efficient storage and retrieval of image data while adhering to the constraints of the data model.</li></ul><p><strong>3. Flexibility and Efficiency</strong></p><ul><li>By creating an ImageData class, you gain flexibility. You can implement additional methods or properties, such as image resizing, compression, or format conversion, within this class without cluttering your main Document model.</li><li>When an image is required, you can easily instantiate it from Data, allowing for lazy loading of images, which can significantly reduce memory usage when displaying documents.</li></ul><h3>Second Step : Adjust your <strong>App</strong> struct</h3><p>Using ModelContainer in this way sets the stage for future development where you can create ViewModels that interact with the data layer. By passing the model context to the DocumentsView, you enable the use of data-binding and state management within the view, facilitating the implementation of the MVVM (Model-View-ViewModel) design pattern.</p><pre>import SwiftUI<br>import SwiftData<br><br>@main<br>struct ScannerProApp: App {<br>    var sharedModelContainer: ModelContainer = {<br>        let schema = Schema([<br>            Document.self, // Define the schema with the Document model<br>        ])<br>        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)<br><br>        do {<br>            // Create a ModelContainer with the specified schema and configuration<br>            return try ModelContainer(for: schema, configurations: [modelConfiguration])<br>        } catch {<br>            fatalError(&quot;Could not create ModelContainer: \(error)&quot;) // Handle errors<br>        }<br>    }()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            // Initialize the main view with the model context from the shared ModelContainer<br>            DocumentsView(modelContext: sharedModelContainer.mainContext)<br>        }<br>        .modelContainer(sharedModelContainer) // Provide the ModelContainer to the SwiftUI environment<br>    }<br>}</pre><p><strong>Key Components</strong></p><p>1. <strong>@main Attribute</strong>:</p><ul><li>This designates the starting point of the application. The ScannerProApp struct conforms to the App protocol, defining the app’s life cycle.</li></ul><p>2. <strong>sharedModelContainer</strong>:</p><ul><li>This property creates a shared instance of ModelContainer, which is essential for managing data models in SwiftData.</li><li>Inside the closure, a schema is defined that includes the Document model. This schema represents the structure of the data that the application will use.</li></ul><p>3. <strong>ModelConfiguration</strong>:</p><ul><li>This configuration specifies settings for the ModelContainer, such as whether the data is stored in memory only. In this case, isStoredInMemoryOnly is set to false, indicating that data should be persisted beyond just memory.</li></ul><p>4. <strong>Error Handling</strong>:</p><ul><li>The do-catch block is used to handle any errors that may occur during the creation of the ModelContainer. If an error arises, the app will terminate with a fatal error message.</li></ul><p>5. <strong>body Property</strong>:</p><ul><li>This property defines the app’s user interface. The WindowGroup is used to present the main view of the application, DocumentsView, passing the main context of the sharedModelContainer as a parameter.</li><li>The .modelContainer(sharedModelContainer) modifier makes the sharedModelContainer available to the SwiftUI view hierarchy, allowing child views to access the model context.</li></ul><h3>Third Step : DocumentsView and his ViewModel</h3><p>Let’s break down the provided code block by block, explaining how it sets up a view using SwiftUI and SwiftData, while also implementing the MVVM architecture with a ViewModel.</p><p><strong>Important</strong>: The @Query macro works only when it can access the SwiftUI environment, which makes it incompatible with MVVM.</p><h4><strong>Block 1: DocumentsView Structure</strong></h4><pre>import SwiftUI<br>import SwiftData<br><br>struct DocumentsView: View {<br>    @State private var viewModel: ViewModel<br>    @State private var path: [Document] = []<br><br>    init(modelContext: ModelContext) {<br>        let viewModel = ViewModel(modelContext: modelContext)<br>        _viewModel = State(initialValue: viewModel)<br>    }</pre><p><strong>Explanation:</strong></p><p>1. <strong>Imports</strong>: The code imports SwiftUI for building the UI and SwiftData for data management.</p><p>2. <strong>Structure Declaration</strong>: The DocumentsView struct conforms to the View protocol, which is fundamental for any SwiftUI view.</p><p>3. <strong>State Properties</strong>:</p><ul><li>@State private var viewModel: ViewModel: This property holds an instance of the ViewModel, which will manage the data and business logic for the view. It is marked with @State to allow SwiftUI to monitor changes to it.</li><li>@State private var path: [Document]: This property is used to maintain a navigation stack of Document objects for navigating between views.</li></ul><p>4. <strong>Initializer</strong>:</p><ul><li>The initializer takes a ModelContext as a parameter, which is essential for accessing and manipulating data within SwiftData.</li><li>It creates a ViewModel instance using the provided modelContext and assigns it to the viewModel state property.</li></ul><h4><strong>Block 2: View Body and Navigation</strong></h4><pre>    var body: some View {<br>        NavigationStack(path: $path) {<br>            List {<br>                ForEach(viewModel.documents) { document in<br>                    NavigationLink(value: document) {<br>                        docRow(for: document)<br>                    }<br>                    .swipeActions(edge: .trailing) {<br>                        Button(role: .destructive, action: {<br>                            viewModel.deleteDoc(document)<br>                        }) {<br>                            Label(&quot;Delete&quot;, systemImage: &quot;trash&quot;)<br>                        }<br>                    }<br>                }<br>            }<br>            .navigationTitle(&quot;Documents&quot;)<br>            .navigationDestination(for: Document.self) { document in<br>                DocumentDetailView(document: document)<br>            }</pre><p><strong>Explanation:</strong></p><p>1. body<strong> Property</strong>: This computed property defines the view’s user interface.</p><p>2. NavigationStack: The NavigationStack manages a navigation hierarchy for the app. The $path binding allows navigation state to be updated dynamically.</p><p>3. List: The List displays a collection of documents.</p><ul><li>ForEach: Iterates over viewModel.documents, creating a row for each document.</li><li>NavigationLink: Provides navigation to the DocumentDetailView when a document row is tapped.</li></ul><p>4. <strong>Swipe Actions</strong>:</p><ul><li>Allows the user to delete a document with a swipe gesture. The deleteDoc method in the ViewModel is called to handle this action.</li></ul><p>5. <strong>Navigation Title</strong>: Sets the title of the navigation bar to “Documents”.</p><p>6. <strong>Navigation Destination</strong>: Specifies that tapping a document will navigate to DocumentDetailView with the selected document.</p><h4><strong>Block 3: Document Row and Scan Button</strong></h4><pre>            .overlay(alignment: .bottomTrailing, content: {<br>                scanButton()<br>            })<br>            .sheet(isPresented: $viewModel.isScannerPresented, content: {<br>                ScannerView { result in<br>                    switch result {<br>                    case .success(let scannedImages):<br>                        viewModel.scanDocSuccess(scannedImages)<br>                    case .failure(let error):<br>                        print(error.localizedDescription)<br>                    }<br>                    viewModel.isScannerPresented = false<br>                } didCancel: {<br>                    viewModel.isScannerPresented = false<br>                }<br>            })<br>        }<br>    }</pre><p><strong>Explanation:</strong></p><p>1. <strong>overlay</strong>: This modifier adds a floating button (the scan button) at the bottom right of the screen.</p><p>2. <strong>scanButton</strong>: This method (defined later) creates a button for initiating the document scanning process.</p><p>3. <strong>sheet</strong>: A modal sheet is presented when isScannerPresented is true, showing the ScannerView. It handles the results of the scanning process:</p><ul><li><strong>On success</strong>, it calls scanDocSuccess with the scanned images.</li><li><strong>On failure</strong>, it prints the error message.</li></ul><h4><strong>Block 4: Document Row Function</strong></h4><pre>    private func docRow(for doc: Document) -&gt; some View {<br>        HStack {<br>            if let preview = doc.preview {<br>                Image(uiImage: preview)<br>                    .resizable()<br>                    .scaledToFill()<br>                    .frame(width: 50, height: 50)<br>                    .clipped()<br>            }<br>            VStack(alignment: .leading, spacing: 5) {<br>                Text(doc.name)<br>                HStack {<br>                    Text(&quot;\(doc.date.formatted(Date.FormatStyle(date: .numeric)))&quot;)<br>                        .font(.system(size: 12))<br>                        .opacity(0.6)<br>                }<br>            }<br>        }<br>    }</pre><p><strong>Explanation:</strong></p><p>1. docRow<strong> Function</strong>: This private function defines how each document row looks in the list.</p><ul><li>It uses a horizontal stack (HStack) to arrange the document’s preview image and text vertically.</li></ul><p>2. <strong>Preview Image</strong>: If a preview image is available, it is displayed as a resizable image with a fixed size.</p><p>3. <strong>Document Information</strong>: Displays the document’s name and its formatted date in a vertical stack (VStack).</p><h4><strong>Block 5: Scan Button Function</strong></h4><pre>    private func scanButton() -&gt; some View {<br>        Button(action: viewModel.showScanner) {<br>            Image(systemName: &quot;doc.viewfinder&quot;)<br>                .resizable()<br>                .frame(width: 30, height: 30)<br>                .padding(25)<br>                .foregroundStyle(.white)<br>                .background(.blue)<br>                .clipShape(Circle())<br>        }<br>        .padding(20)<br>    }<br>}</pre><p><strong>Explanation:</strong></p><p>1. <strong>scanButton()</strong> : This private function creates a circular button that, when tapped, triggers the showScanner method in the ViewModel to present the scanning interface.</p><p>2. <strong>Button Styling</strong>: The button uses a system image for the icon, with custom styling for padding, color, and shape.</p><h4><strong>Block 6: ViewModel Implementation</strong></h4><pre>extension DocumentsView {<br>    @Observable<br>    class ViewModel {<br>        var modelContext: ModelContext<br>        var documents = [Document]()<br><br>        var isScannerPresented: Bool = false<br><br>        init(modelContext: ModelContext) {<br>            self.modelContext = modelContext<br>            fetchData()<br>        }</pre><p><strong>Explanation:</strong></p><p>To move this over to MVVM we need to create a view model class using the @Observable macro. This needs to be able to perform a SwiftData fetch when it loads, but also to repeat that fetch in the future when the data changes.</p><p>1. <strong>Extension</strong>: The ViewModel class is defined within an extension of DocumentsView, keeping the naming simple and clear.</p><p>2. <strong>@Observable</strong>: This macro allows the ViewModel to automatically notify the view when its properties change.</p><p>3. <strong>Properties</strong>:</p><ul><li>modelContext: The context used for data operations, passed in from the view.</li><li>documents: An array to store fetched Document objects.</li><li>isScannerPresented: A boolean to control the display of the scanner interface.</li></ul><p>4. <strong>Initializer</strong>: Accepts a ModelContext, initializes the modelContext property, and fetches initial data with fetchData().</p><h4><strong>Block 7: Fetching Data</strong></h4><pre>        func fetchData() {<br>            do {<br>                let descriptor = FetchDescriptor&lt;Document&gt;(sortBy: [SortDescriptor(\.date, order: .reverse)])<br>                documents = try modelContext.fetch(descriptor)<br>            } catch {<br>                print(&quot;Fetch failed&quot;)<br>            }<br>        }</pre><p><strong>Explanation:</strong></p><p>Your view model doesn’t need to perform a complete fetch for every change you make, but you do need some way to make sure its data stays up to date over time.</p><p>1. <strong>fetchData Method</strong>: This function retrieves documents from the model context.</p><ul><li>It creates a FetchDescriptor to define how to sort the results (by date in descending order).</li><li>The fetched documents are assigned to the documents property.</li><li>Errors during fetching are caught and logged.</li></ul><h4><strong>Block 8: Handling Scanner and Deleting Documents</strong></h4><pre>        func showScanner() {<br>            isScannerPresented.toggle()<br>        }<br><br>        func scanDocSuccess(_ scannedImages: [UIImage]) {<br>            let imageDataArray = scannedImages.map {<br>                ImageData(imageData: $0.pngData()!)<br>            }<br><br>            let doc = Document(<br>                name: &quot;Document&quot;,<br>                images: imageDataArray,<br>                date: Date()<br>            )<br>            modelContext.insert(doc)<br>            fetchData()<br>        }<br><br>        func deleteDoc(_ document: Document) {<br>            withAnimation {<br>                modelContext.delete(document)<br>            }<br>            fetchData()<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><p>1. showScanner<strong> Method</strong>: This toggles the isScannerPresented property to show or hide the scanner interface.</p><p>2. scanDocSuccess<strong> Method</strong>: This method processes scanned images:</p><ul><li>Converts the images into ImageData objects.</li><li>Creates a new Document instance and inserts it into the model context.</li><li>Calls fetchData to refresh the documents list.</li></ul><p>3. deleteDoc<strong> Method</strong>: This method deletes a specified document from the model context using animation, then refreshes the documents list by calling fetchData.</p><h4><strong>Conclusion</strong></h4><p>This implementation showcases how to set up a SwiftUI view with a ViewModel using SwiftData, while adhering to the MVVM architecture. By utilizing @Observable and ModelContext, the ViewModel efficiently manages the data for the view, ensuring that it remains up-to-date while keeping the UI responsive and maintainable. The approach of placing the ViewModel in an extension helps maintain clean and organized code, simplifying reference in the view.</p><h3>Fourth Step : Scanner Implementation</h3><p>Here’s a detailed explanation of the provided code for a document scanner view using SwiftUI and VisionKit, structured in a single block:</p><pre>import SwiftUI<br>import VisionKit<br><br>struct ScannerView: UIViewControllerRepresentable {<br>    let didFinishWith: ((_ result: Result&lt;[UIImage], Error&gt;) -&gt; Void)<br>    let didCancel: () -&gt; Void<br><br>    func makeUIViewController(context: Context) -&gt; VNDocumentCameraViewController {<br>        let scannerViewController = VNDocumentCameraViewController()<br>        scannerViewController.delegate = context.coordinator<br>        return scannerViewController<br>    }<br><br>    func updateUIViewController(_ uiViewController: VNDocumentCameraViewController, context: Context) { }<br><br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(with: self)<br>    }<br><br>    class Coordinator: NSObject, VNDocumentCameraViewControllerDelegate {<br>        let scannerView: ScannerView<br><br>        init(with scannerView: ScannerView) {<br>            self.scannerView = scannerView<br>        }<br><br>        // The camera successfully completed a scan.<br>        func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {<br>            let scannedPages: [UIImage] = (0..&lt;scan.pageCount).compactMap { scan.imageOfPage(at: $0) }<br>            scannerView.didFinishWith(.success(scannedPages))<br>        }<br><br>        // The user canceled out of the document camera interface.<br>        func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {<br>            scannerView.didCancel()<br>        }<br><br>        // The document scan failed or was unable to capture a photo.<br>        func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFailWithError error: Error) {<br>            scannerView.didFinishWith(.failure(error))<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><p>This code defines a ScannerView that acts as a bridge between SwiftUI and the UIKit component VNDocumentCameraViewController, allowing users to scan documents using their device’s camera.</p><p>1. <strong>Imports</strong>: The code imports SwiftUI for building the user interface and VisionKit for document scanning functionality.</p><p>2. <strong>ScannerView Structure</strong>:</p><ul><li>The ScannerView struct conforms to UIViewControllerRepresentable, which allows it to wrap a UIKit view controller (in this case, the document camera).</li></ul><p>• <strong>Properties</strong>:</p><ul><li>didFinishWith: A closure that handles the result of the scanning operation, returning an array of scanned images or an error.</li><li>didCancel: A closure that is called when the user cancels the scanning process.</li></ul><p>3. <strong>makeUIViewController Method</strong>:</p><ul><li>This method creates and configures an instance of VNDocumentCameraViewController.</li><li>The delegate is set to a coordinator (created below) to handle callbacks from the camera.</li></ul><p>4. <strong>updateUIViewController Method</strong>:</p><ul><li>This method is required by UIViewControllerRepresentable but is empty here since there’s no need to update the camera view controller after it has been created.</li></ul><p>5. <strong>makeCoordinator Method</strong>:</p><ul><li>This method creates an instance of the Coordinator class, which will handle delegate methods for the document camera.</li></ul><p>6. <strong>Coordinator Class</strong>:</p><ul><li>The Coordinator class, conforming to VNDocumentCameraViewControllerDelegate, is responsible for handling the results of the document scanning process.</li></ul><p>• <strong>Properties</strong>:</p><ul><li>scannerView: A reference to the parent ScannerView, allowing it to communicate back with the parent.</li></ul><p>• <strong>Methods</strong>:</p><ul><li>documentCameraViewController(_:didFinishWith:): Called when scanning is completed successfully. It retrieves the scanned pages as UIImage and invokes the didFinishWith closure with the success result.</li><li>documentCameraViewControllerDidCancel(_): Called when the user cancels the scan. It invokes the didCancel closure.</li><li>documentCameraViewController(_:didFailWithError:): Called when scanning fails. It passes the error back through the didFinishWith closure.</li></ul><p><strong>Conclusion</strong></p><p>This implementation effectively encapsulates the document scanning functionality in a SwiftUI-compatible structure, leveraging UIKit’s VNDocumentCameraViewController for a seamless scanning experience. By using a coordinator pattern, the code maintains a clean separation between the SwiftUI view and the UIKit delegate methods, facilitating a smooth integration of UIKit components within a SwiftUI environment.</p><h3>Fifth Step : DocumentDetailView and his ViewModel</h3><p>Here’s a breakdown of the provided SwiftUI code, separating the view (DocumentDetailView) and its view model (ViewModel) into distinct sections, with a brief description at the beginning:</p><p><strong>Description</strong></p><p>This code implements a document detail view for a scanning application, allowing users to view images from a document, rename it, share it as a PDF, and print it. The view utilizes a ViewModel to manage the state and business logic.</p><h4><strong>View: DocumentDetailView</strong></h4><pre>import SwiftUI<br>import SwiftData<br><br>struct DocumentDetailView: View {<br>    @StateObject private var viewModel: ViewModel<br>    @State private var showImageList = false<br>    var document: Document<br><br>    init(document: Document) {<br>        _viewModel = StateObject(wrappedValue: ViewModel())<br>        self.document = document<br>    }<br><br>    var body: some View {<br>        HStack {<br>            ScrollView {<br>                VStack {<br>                    ForEach(document.images, id: \.imageData) { imageData in<br>                        if let image = imageData.image {<br>                            Image(uiImage: image)<br>                                .resizable()<br>                                .scaledToFit()<br>                                .frame(maxWidth: .infinity)<br>                        }<br>                    }<br>                }<br>            }<br>            Spacer()<br>            VStack {<br>                if showImageList {<br>                    VStack(spacing: 10) {<br>                        Text(&quot;\(document.images.count) pages&quot;)<br>                            .font(.system(size: 12))<br>                            .foregroundStyle(.secondary)<br>                        ScrollView {<br>                            ForEach(document.images, id: \.imageData) { imageData in<br>                                if let image = imageData.image {<br>                                    Image(uiImage: image)<br>                                        .resizable()<br>                                        .scaledToFit()<br>                                        .frame(width: 100, height: 100)<br>                                        .padding(.bottom, 10)<br>                                }<br>                            }<br>                        }<br>                    }<br>                    .frame(maxWidth: 125)<br>                    .background(Color.gray.opacity(0.2))<br>                }<br>                Spacer()<br>            }<br>            Spacer()<br>        }<br>        .navigationBarTitleDisplayMode(.inline)<br>        .toolbar {<br>            ToolbarItem(placement: .principal) {<br>                Menu {<br>                    Button(action: {<br>                        viewModel.showRenameAlert()<br>                    }) {<br>                        Label(&quot;Rename&quot;, systemImage: &quot;pencil&quot;)<br>                    }<br>                    ShareLink(item: viewModel.generatePDF(from: document.images.compactMap { $0.image })!) {<br>                        Label(&quot;Share&quot;, systemImage: &quot;square.and.arrow.up&quot;)<br>                    }<br>                    Button(action: {<br>                        viewModel.printDocument(document: document)<br>                    }) {<br>                        Label(&quot;Print&quot;, systemImage: &quot;printer&quot;)<br>                    }<br>                } label: {<br>                    HStack {<br>                        Text(document.name)<br>                            .bold()<br>                        Image(systemName: &quot;chevron.down.circle.fill&quot;)<br>                    }<br>                }<br>            }<br>            ToolbarItem(placement: .navigationBarTrailing) {<br>                Button(action: {<br>                    withAnimation {<br>                        showImageList.toggle()<br>                    }<br>                }) {<br>                    Image(systemName: &quot;list.bullet&quot;)<br>                }<br>            }<br>        }<br>        .alert(&quot;Rename the document&quot;, isPresented: $viewModel.isRenameAlertPresented) {<br>            TextField(&quot;&quot;, text: $viewModel.newDocumentName)<br>            Button(&quot;OK&quot;) { viewModel.changeDocName(document) }<br>            Button(&quot;Cancel&quot;, role: .cancel) {}<br>        }<br>    }<br>}</pre><h4><strong>View Model: ViewModel</strong></h4><pre>import Foundation<br>import SwiftUI<br>import SwiftData<br>import PDFKit<br><br>extension DocumentDetailView {<br>    class ViewModel: ObservableObject {<br>        @Published var newDocumentName: String = &quot;&quot;<br>        @Published var isRenameAlertPresented: Bool = false<br><br>        func showRenameAlert() {<br>            isRenameAlertPresented.toggle()<br>        }<br><br>        func changeDocName(_ document: Document) {<br>            if !newDocumentName.isEmpty {<br>                document.name = newDocumentName<br>            }<br>        }<br><br>        func generatePDF(from images: [UIImage]) -&gt; URL? {<br>            let pdfDocument = PDFDocument()<br><br>            for (index, image) in images.enumerated() {<br>                let pdfPage = PDFPage(image: image)<br>                pdfDocument.insert(pdfPage!, at: index)<br>            }<br><br>            // Save the PDF to the temporary folder<br>            let tempDirectory = FileManager.default.temporaryDirectory<br>            let pdfURL = tempDirectory.appendingPathComponent(UUID().uuidString).appendingPathExtension(&quot;pdf&quot;)<br><br>            do {<br>                try pdfDocument.dataRepresentation()?.write(to: pdfURL)<br>                return pdfURL<br>            } catch {<br>                print(&quot;Erreur lors de la génération du PDF : \(error)&quot;)<br>                return nil<br>            }<br>        }<br><br>        func printDocument(document: Document) {<br>            // Check if the document contains images<br>            guard !document.images.isEmpty else {<br>                print(&quot;Aucune image à imprimer&quot;)<br>                return<br>            }<br><br>            // Create an array of UIImages from document data<br>            let imagesToPrint = document.images.compactMap { $0.image }<br><br>            // Generate a PDF from images<br>            if let pdfURL = generatePDF(from: imagesToPrint) {<br>                // Create a UIPrintInteractionController to handle printing<br>                let printController = UIPrintInteractionController.shared<br><br>                // Configure print information<br>                let printInfo = UIPrintInfo(dictionary: nil)<br>                printInfo.jobName = document.name<br>                printInfo.outputType = .general<br>                printController.printInfo = printInfo<br><br>                // Provide the content to print (the PDF file)<br>                if let pdfData = try? Data(contentsOf: pdfURL) {<br>                    printController.printingItem = pdfData<br>                } else {<br>                    print(&quot;Erreur lors de la récupération des données du PDF&quot;)<br>                }<br><br>                // Show Print Dialog<br>                printController.present(animated: true, completionHandler: nil)<br>            } else {<br>                print(&quot;Erreur lors de la génération du PDF pour l&#39;impression&quot;)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Explanation :</strong></p><p>• <strong>View</strong>: The DocumentDetailView struct defines the user interface, which includes a scrollable view for displaying images, a toolbar for actions (renaming, sharing, printing), and a button to toggle the image list display.</p><p>• <strong>View Model</strong>: The ViewModel class manages the document’s state and logic, including renaming the document, generating a PDF from images, and handling print functionality. It utilizes @Published properties to update the UI when state changes.</p><p>This separation of concerns ensures a clear structure, where the view handles presentation and user interaction, while the view model manages data and business logic.</p><h3>Conclusion</h3><p>In conclusion, this project has been a rewarding journey into developing a robust document scanning application using SwiftUI and SwiftData. It showcases various features, including image scanning, document management, and PDF generation, aimed at enhancing user experience. I hope this article has provided valuable insights into the development process and the architecture involved in building such an application. For those interested in exploring the complete code, feel free to visit my GitHub repository at <a href="https://github.com/alucchini/App-Scanner-iOS">[App-Scanner-iOS]</a>. Thank you for reading, and you can also connect with me on LinkedIn at <a href="https://www.linkedin.com/in/antoine-lucchini-573178178/">[Antoine Lucchini]</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b47b76b57a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>