<?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 Sagar Vaholiya on Medium]]></title>
        <description><![CDATA[Stories by Sagar Vaholiya on Medium]]></description>
        <link>https://medium.com/@sagarvaholiya?source=rss-6c9f20f4c5cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TH4aowK5f_urXzLH.</url>
            <title>Stories by Sagar Vaholiya on Medium</title>
            <link>https://medium.com/@sagarvaholiya?source=rss-6c9f20f4c5cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:34:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sagarvaholiya/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[Building a Responsive view in SwiftUI with ViewThatFits]]></title>
            <link>https://medium.com/@sagarvaholiya/building-a-responsive-view-in-swiftui-with-viewthatfits-bf36006e87a3?source=rss-6c9f20f4c5cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf36006e87a3</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[responsive-layout]]></category>
            <category><![CDATA[viewthatfits]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sagar Vaholiya]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 18:45:11 GMT</pubDate>
            <atom:updated>2025-08-29T18:45:11.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*1Q9ZRq0YG0HxWV0jgenjpA.png" /></figure><h3>Introduction</h3><p>Designing responsive layouts in SwiftUI can be tricky. Often, a layout that looks great on a wide screen feels cramped on smaller devices. Traditionally, this required GeometryReader or manual size checks.</p><p>With <strong>ViewThatFits</strong>, SwiftUI 4 introduces a simpler way to create <strong>fallback layouts</strong>. You provide multiple versions of a view, and SwiftUI automatically chooses the first one that fits the available space.</p><h3>A Simple Example</h3><pre>ViewThatFits {<br>    Text(&quot;This text fits in one line&quot;)<br>        .lineLimit(1)<br><br>    Text(&quot;This text fits in two lines&quot;)<br>        .lineLimit(2)<br>}</pre><ul><li>If the container is wide enough, SwiftUI shows the one-line version.</li><li>If the width is limited, it falls back to the two-line version automatically.</li></ul><p>This declarative approach saves you from writing conditional layout logic manually.</p><h3>Real-World Scenario: Responsive Toolbar</h3><p>Imagine building a <strong>toolbar</strong> with a profile section and a settings button. On wide screens, you want them arranged horizontally. On narrow screens, you want them stacked vertically.</p><p>We can achieve this elegantly with ViewThatFits.</p><h3>Step 1: Create the ResponsiveToolbar View</h3><pre>struct ResponsiveToolbar: View {<br>    var body: some View {<br>        ViewThatFits {<br>            // Wide layout<br>            HStack {<br>                profileSection<br>                Spacer()<br>                settingsButton<br>            }<br>            .padding()<br><br>            // Compact layout<br>            VStack {<br>                profileSection<br>                settingsButton<br>            }<br>            .padding()<br>        }<br>        .background(.ultraThinMaterial)<br>        .cornerRadius(12)<br>        .padding()<br>    }<br><br>    private var profileSection: some View {<br>        HStack {<br>            Image(systemName: &quot;person.circle.fill&quot;)<br>                .resizable()<br>                .frame(width: 40, height: 40)<br>                .foregroundColor(.blue)<br>            Text(&quot;John Doe&quot;)<br>                .font(.headline)<br>        }<br>    }<br><br>    private var settingsButton: some View {<br>        Button(action: {}) {<br>            Label(&quot;Settings&quot;, systemImage: &quot;gearshape.fill&quot;)<br>        }<br>        .buttonStyle(.borderedProminent)<br>    }<br>}</pre><ul><li>The first child of ViewThatFits is an <strong>HStack</strong> for wide screens.</li><li>The second child is a <strong>VStack</strong> for narrow screens.</li><li>SwiftUI picks the layout that fits the current container automatically.</li></ul><h3>Step 2: Let’s make it interactive</h3><p>To see ViewThatFits in action, we can adjust the toolbar width dynamically using a slider. This lets you watch the layout switch between horizontal and vertical in real time.</p><pre>struct ContentView: View {<br>    @State private var toolbarWidth: CGFloat = 300<br><br>    var body: some View {<br>        VStack(spacing: 30) {<br>            Text(&quot;Responsive Toolbar Demo&quot;)<br>                .font(.title2)<br>                .bold()<br><br>            ResponsiveToolbar()<br>                .frame(width: toolbarWidth, height: 150)<br>                .border(Color.gray)<br>                .animation(.easeInOut, value: toolbarWidth)<br><br>            Slider(value: $toolbarWidth, in: 200...400, step: 1) {<br>                Text(&quot;Width&quot;)<br>            }<br>            .padding()<br><br>            Text(&quot;Current width: \(Int(toolbarWidth))&quot;)<br>                .font(.footnote)<br>                .foregroundColor(.secondary)<br>        }<br>        .padding()<br>    }<br>}</pre><ul><li>The slider lets you shrink or expand the container width between 200 and 400 points.</li><li>When the width is large, the HStack layout is used.</li><li>When the width is small, SwiftUI automatically falls back to the VStack layout.</li><li>.animation(.easeInOut, value: toolbarWidth) ensures a smooth transition.</li></ul><h3>Step 3: Test and Explore</h3><ul><li>Run the app on different devices or in the Canvas preview.</li><li>Drag the slider to see the toolbar switch layouts.</li><li>You can use this pattern for toolbars, cards, buttons with icons, or any UI that needs to adapt gracefully to varying space.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*3NMmh3AdvXuTaeuJ62n17Q.gif" /><figcaption>Result</figcaption></figure><h3>Key Takeaways</h3><ul><li><strong>ViewThatFits</strong> is perfect for <strong>content-driven fallback layouts</strong>.</li><li>It reduces complexity compared to manually checking available space or device orientation.</li><li>Combine it with sliders or other dynamic containers to <strong>preview responsive behavior</strong> interactively.</li><li>For <strong>device orientation-specific</strong> layouts, combine ViewThatFits with horizontalSizeClass from the environment.</li></ul><h3>Conclusion</h3><p><strong>ViewThatFits</strong> makes responsive SwiftUI design simpler, cleaner, and more declarative. By combining it with interactive previews like sliders, you can see how your UI adapts in real time, a huge improvement over guessing layout behaviour on different devices.</p><p>Try it in your next SwiftUI project and watch your layouts adapt seamlessly!</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf36006e87a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Multiple Child View Events in SwiftUI with Enums]]></title>
            <link>https://medium.com/@sagarvaholiya/handling-multiple-child-view-events-in-swiftui-with-enums-e9db027adc1c?source=rss-6c9f20f4c5cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9db027adc1c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[closu]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[even]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sagar Vaholiya]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 11:08:32 GMT</pubDate>
            <atom:updated>2025-08-25T11:08:32.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚨 The Problem</h3><p>When building SwiftUI apps, you often have a <strong>Parent View</strong> that hosts a <strong>Child View</strong>. The child might have multiple buttons (e.g., <em>Edit</em>, <em>Delete</em>, <em>Share</em>) and needs to tell the parent <strong>what just happened</strong>.</p><p>One common solution is to give the child multiple closures:</p><pre>struct ChildView: View {<br>    var onEdit: () -&gt; Void<br>    var onDelete: () -&gt; Void<br>    var onShare: () -&gt; Void<br>    ...<br>}</pre><p>But this quickly becomes messy, especially when the number of events grows.</p><h3>🌟 The Enum-Based Approach</h3><p>Instead of passing multiple closures, we can define <strong>one closure</strong> that accepts an <strong>enum</strong> describing the event. This keeps code clean, extensible, and easier to maintain.</p><h3>Step 1: Define Your Events</h3><pre>enum ChildEvent {<br>    case edit<br>    case delete<br>    case share<br>}</pre><h3>Step 2: Child View with a Single Closure</h3><pre>struct ChildView: View {<br>    var onEvent: (ChildEvent) -&gt; Void<br><br>    var body: some View {<br>        HStack(spacing: 20) {<br>            Button(&quot;✏️ Edit&quot;) {<br>                onEvent(.edit)<br>            }<br><br>            Button(&quot;🗑 Delete&quot;) {<br>                onEvent(.delete)<br>            }<br><br>            Button(&quot;📤 Share&quot;) {<br>                onEvent(.share)<br>            }<br>        }<br>        .padding()<br>        .background(Color(.systemGray6))<br>        .cornerRadius(10)<br>    }<br>}</pre><h3>Step 3: Parent View Handles Events</h3><pre>struct ParentView: View {<br>    var body: some View {<br>        VStack(spacing: 30) {<br>            Text(&quot;📱 Parent View&quot;)<br>                .font(.title)<br>                .padding()<br><br>            ChildView { event in<br>                handleChildEvent(event)<br>            }<br>        }<br>    }<br><br>    private func handleChildEvent(_ event: ChildEvent) {<br>        switch event {<br>        case .edit:<br>            print(&quot;Editing item…&quot;)<br>        case .delete:<br>            print(&quot;Deleting item…&quot;)<br>        case .share:<br>            print(&quot;Sharing item…&quot;)<br>        }<br>    }<br>}</pre><h3>Real-World Example in Action</h3><p>Imagine you’re building a <strong>To-Do List App</strong>. Each task has buttons to edit, delete, or share. Instead of giving ChildView 3 separate closures, you pass just one.</p><p>This makes your child views <strong>lighter</strong> and parent views <strong>smarter</strong>.</p><h3>✅ Benefits of Enum-Based Events</h3><ul><li>🚀 <strong>Scalable</strong>: Adding new events? Just add a new enum case.</li><li>🎯 <strong>Single Closure</strong>: No closure explosion in the child view.</li><li>🧼 <strong>Cleaner Code</strong>: Easier to read &amp; maintain.</li><li>🔄 <strong>Reusable</strong>: ChildView stays generic, Parent decides behavior.</li></ul><h3>🔹 TL;DR</h3><p>Instead of passing multiple closures for multiple child view actions, use an <strong>enum + single closure</strong>. It’s cleaner, scalable, and keeps your SwiftUI code easy to manage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9db027adc1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Growing & Shrinking Animations in SwiftUI with @Namespace]]></title>
            <link>https://medium.com/@sagarvaholiya/growing-shrinking-animations-in-swiftui-with-namespace-f1b644994c18?source=rss-6c9f20f4c5cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1b644994c18</guid>
            <category><![CDATA[ios-animation]]></category>
            <category><![CDATA[ui-transition]]></category>
            <category><![CDATA[matchedgeometryeffect]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sagar Vaholiya]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 14:38:22 GMT</pubDate>
            <atom:updated>2025-08-20T14:48:30.794Z</atom:updated>
            <content:encoded><![CDATA[<h3>✨ Why Animations Matter</h3><p>Animations are the secret sauce behind a delightful user experience. They give life to your UI, guide the user’s attention, and make interactions feel smooth and intuitive.</p><p>In SwiftUI, one of the most magical tricks is combining <strong>@Namespace</strong> with <strong>matchedGeometryEffect</strong> to animate elements seamlessly between views. This allows elements to <strong>grow, shrink, and move</strong> naturally without complex manual calculations.</p><h3>📽️ The Scenario</h3><p>Imagine a <strong>Movie List screen</strong>:</p><ol><li>You see a scrollable list of movies — posters with titles.</li><li>Tap on a movie → its poster <strong>grows</strong> and transitions into a <strong>detail view</strong>.</li><li>Close the detail → poster <strong>shrinks</strong> back into its place.</li></ol><p>This pattern makes your UI feel alive and polished.</p><h3>🛠️ How It Works</h3><ol><li><strong>Namespace</strong>: A unique identifier to link views across screens.</li><li><strong>matchedGeometryEffect</strong>: Tells SwiftUI that two views represent the same element and animates position, size, and shape changes between them.</li></ol><p>By combining these, you can grow, shrink, or even morph UI elements without jumping through hoops.</p><h3>💻 Implementation</h3><h4>1️⃣ Movie Model</h4><pre>struct Movie: Identifiable {<br>    let id = UUID()<br>    let title: String<br>    let subTitle: String<br>    let image: String<br>}</pre><h4>2️⃣ Detail View with Matched Geometry</h4><pre>struct MovieDetailView: View {<br>    let movie: Movie<br>    var animation: Namespace.ID<br>    @Binding var selectedMovie: Movie?<br><br>    var body: some View {<br>        VStack {<br>            Image(movie.image)<br>                .resizable()<br>                .scaledToFit()<br>                .frame(height: 400)<br>                .cornerRadius(16)<br>                .matchedGeometryEffect(id: movie.id, in: animation)<br><br>            Text(movie.title)<br>                .font(.largeTitle)<br>                .fontWeight(.bold)<br>                .padding(.top)<br><br>            Text(movie.subTitle)<br>                .font(.title3)<br>                .foregroundColor(.secondary)<br>                .padding(.bottom, 20)<br><br>            Spacer()<br><br>            Button(&quot;Close&quot;) {<br>                withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {<br>                    selectedMovie = nil<br>                }<br>            }<br>        }<br>        .padding()<br>        .frame(maxWidth: .infinity, maxHeight: .infinity)<br>        .background(Color(.systemBackground))<br>    }<br>}</pre><h4>3️⃣ Movie List View with Growing/Shrinking Posters</h4><pre>struct MovieListView: View {<br>    @Namespace private var animation<br>    @State private var selectedMovie: Movie?<br>    @State private var showDetail = false<br>    <br>    let movies = [<br>        Movie(title: &quot;Inception&quot;, subTitle: &quot;A thief who steals corporate secrets&quot;, image: &quot;inception&quot;),<br>        Movie(title: &quot;Interstellar&quot;, subTitle: &quot;Nolan&#39;s Odyssey&quot;, image: &quot;interstellar&quot;),<br>        Movie(title: &quot;Superman&quot;, subTitle: &quot;Look up.&quot;, image: &quot;superman&quot;),<br>        Movie(title: &quot;Alien: Earth&quot;, subTitle: &quot;We were safer in space.&quot;, image: &quot;alien&quot;),<br>        Movie(title: &quot;Jurassic World Rebirth&quot;, subTitle: &quot;A new era is born.&quot;, image: &quot;jurassic&quot;),<br>        Movie(title: &quot;Weapons&quot;, subTitle: &quot;Last night at 2:17 AM, every child from Mrs. Gandy&#39;s class woke up, got out of bed, went downstairs, opened the front door, walked into the dark ...and they never came back.&quot;, image: &quot;weapons&quot;),<br>        Movie(title: &quot;Wednesday&quot;, subTitle: &quot;The wait has been torture.&quot;, image: &quot;wednesday&quot;),<br>        Movie(title: &quot;Interstellar&quot;, subTitle: &quot;Nolan&#39;s Odyssey&quot;, image: &quot;interstellar&quot;)<br>    ]<br>    <br>    var body: some View {<br>        ScrollView {<br>            LazyVStack {<br>                ForEach(movies) { movie in<br>                    VStack {<br>                        if selectedMovie?.id == movie.id {<br>                            Color.clear.frame(height: 200)<br>                        } else {<br>                            HStack(alignment: .top, spacing: 20) {<br>                                Image(movie.image)<br>                                    .resizable()<br>                                    .scaledToFit()<br>                                    .frame(width: 120, height: 180)<br>                                    .cornerRadius(8)<br>                                    .padding(.leading, 10)<br>                                    .matchedGeometryEffect(id: movie.id, in: animation)<br>                                    .onTapGesture {<br>                                        withAnimation(.spring(response: 0.5, dampingFraction: 0.8)) {<br>                                            selectedMovie = movie<br>                                        }<br>                                    }<br><br>                                VStack(alignment: .leading, spacing: 5) {<br>                                    Text(movie.title)<br>                                        .font(.title2)<br>                                        .fontWeight(.bold)<br>                                    Text(movie.subTitle)<br>                                        .fontWeight(.semibold)<br>                                        .foregroundColor(.secondary)<br>                                }<br>                            }<br>                            .frame(maxWidth: .infinity, alignment: .leading)<br>                            .padding(.trailing, 10)<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>        .overlay {<br>            if let movie = selectedMovie {<br>                MovieDetailView(<br>                    movie: movie,<br>                    animation: animation,<br>                    selectedMovie: $selectedMovie<br>                )<br>            }<br>        }<br>    }<br>}</pre><h3>It will look like this</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MXs4xWg7eRdDpBytdhKmcw.gif" /></figure><h3>🔹 TL;DR</h3><ul><li><strong>@Namespace + matchedGeometryEffect</strong> enables smooth grow &amp; shrink animations.</li><li>Elements feel alive as they move between screens.</li><li>Perfect for lists, cards, or any transition where continuity matters.</li></ul><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1b644994c18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Managing Root View Transitions in SwiftUI with AppRootManager]]></title>
            <link>https://medium.com/@sagarvaholiya/managing-root-view-transitions-in-swiftui-with-approotmanager-402260281894?source=rss-6c9f20f4c5cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/402260281894</guid>
            <dc:creator><![CDATA[Sagar Vaholiya]]></dc:creator>
            <pubDate>Sun, 25 May 2025 19:47:58 GMT</pubDate>
            <atom:updated>2025-05-25T19:47:58.822Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling Scene Flow Dynamically Using View Injection Pattern</h3><h3>🚨 The Challenge</h3><p>In SwiftUI, switching the root view dynamically — like moving from a login screen to a main app tab bar — isn’t straightforward. Unlike UIKit’s window.rootViewController, SwiftUI doesn’t offer a built-in way to change the root view once it’s set in @main.</p><p>This creates friction when you need to transition the user from:</p><ul><li>Splash → Onboarding → Login</li><li>Login → Main App UI</li><li>Logout → Login screen again</li></ul><p>You might’ve tried hacks like changing the AppStorage keys or setting up massive conditional views inside WindowGroup. But those approaches quickly become messy and unmanageable.</p><h3>🌟 Introducing AppRootManager (A Pattern, Not a Framework!)</h3><blockquote><em>🧠 </em><strong><em>Note</em></strong><em>: </em><em>AppRootManager is </em><strong><em>not</em></strong><em> a built-in class or part of SwiftUI. It’s a clean, reusable </em><strong><em>pattern</em></strong><em> that injects root-level views dynamically using observable state.</em></blockquote><p>With this approach, you build an AppRootManager class that conforms to ObservableObject, and drives which view is shown as the root via a simple enum and @Published property.</p><h3>🧱 Step-by-Step Implementation</h3><pre>enum RootScene {<br>    case splash, login, mainApp<br>}<br><br>final class AppRootManager: ObservableObject {<br>    @Published var currentScene: RootScene = .splash<br><br>    func switchToLogin() {<br>        currentScene = .login<br>    }<br><br>    func switchToMainApp() {<br>        currentScene = .mainApp<br>    }<br>}</pre><h3>🏗️ Inject into App Entry Point</h3><pre>@main<br>struct MyApp: App {<br>    @StateObject private var appRootManager = AppRootManager()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            RootSceneView()<br>                .environmentObject(appRootManager)<br>        }<br>    }<br>}</pre><h3>🔄 RootSceneView.swift — Dynamic View Switcher</h3><pre>struct RootSceneView: View {<br>    @EnvironmentObject var appRootManager: AppRootManager<br><br>    var body: some View {<br>        switch appRootManager.currentScene {<br>        case .splash:<br>            SplashView()<br>        case .login:<br>            LoginView()<br>        case .mainApp:<br>            MainAppTabView()<br>        }<br>    }<br>}</pre><h3>🔐 From Splash to Login</h3><pre>struct SplashView: View {<br>    @EnvironmentObject var appRootManager: AppRootManager<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Welcome to the App&quot;)<br>            Button(&quot;Continue&quot;) {<br>                appRootManager.switchToLogin()<br>            }<br>        }<br>    }<br>}</pre><h3>✅ From Login to Main App</h3><pre>struct LoginView: View {<br>    @EnvironmentObject var appRootManager: AppRootManager<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Login Screen&quot;)<br>            Button(&quot;Login&quot;) {<br>                // Authenticate then...<br>                appRootManager.switchToMainApp()<br>            }<br>        }<br>    }<br>}</pre><h3>🧠 What Pattern Are We Using Here?</h3><p>This architecture follows a <strong>View Injection Pattern</strong>:</p><ul><li>You define root-level views outside your feature modules.</li><li>Root content is injected based on observable state.</li><li>View switching happens in a centralized way.</li></ul><p>Benefits:</p><ul><li>✅ Decouples app flow control from views</li><li>✅ Testable and previewable root logic</li><li>✅ Scales well as new scenes are added (onboarding, reset password, etc.)</li></ul><h3>🔹 TL;DR</h3><p><strong>AppRootManager Pattern in SwiftUI</strong>:</p><ul><li>🚫 No direct support to change root views — this is a workaround</li><li>🔁 ObservableObject + Enum = flexible root view injection</li><li>🧼 Centralizes navigation logic for better maintainability</li><li>💡 Clean, scalable, and preview-friendly architecture</li></ul><h3>📦 Download Starter ProjectSwiftUI, Root View, App Navigation, Scene Flow, View Injection, AppRootManager, Clean Architecture</h3><p><a href="https://github.com/sagar-vaholiya/AppRootManagerDemo/tree/master">Download AppRootManager SwiftUI Demo (ZIP)</a></p><p>Do you currently hard-code navigation in SwiftUI? Try this pattern out and let me know how it goes!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=402260281894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Dynamic UI with AnyLayout in SwiftUI]]></title>
            <link>https://medium.com/@sagarvaholiya/simplifying-dynamic-ui-with-anylayout-in-swiftui-f46d6ab70310?source=rss-6c9f20f4c5cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f46d6ab70310</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[anylayout]]></category>
            <category><![CDATA[ios-16]]></category>
            <category><![CDATA[adaptive-layout]]></category>
            <category><![CDATA[view-composition]]></category>
            <dc:creator><![CDATA[Sagar Vaholiya]]></dc:creator>
            <pubDate>Thu, 01 May 2025 07:27:35 GMT</pubDate>
            <atom:updated>2025-05-01T07:27:35.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlock Seamless Layout Switching with One Line of Code</h3><h3>🚀 Why You Should Care</h3><p>When building UI in SwiftUI, you often need to switch between layout types like HStack, VStack, or even grids depending on screen size, orientation, or accessibility settings. Without a common abstraction, this results in repetitive code and poor maintainability.</p><p><strong>AnyLayout</strong> solves this by allowing you to dynamically swap layout containers at runtime — cleanly and without code duplication.</p><h3>🔮 What is AnyLayout?</h3><p>Introduced in <strong>iOS 16</strong>, AnyLayout is a type-erased layout wrapper. It can hold any layout conforming to the Layoutprotocol like HStackLayout, VStackLayout, ZStackLayout, or even custom layouts.</p><h3>🔧 Basic Example: Responsive Button Layout</h3><pre>struct LayoutToggleView: View {<br>    @State private var isGrid = false<br><br>    var body: some View {<br>        VStack {<br>            Toggle(&quot;Grid Layout&quot;, isOn: $isGrid)<br>                .padding()<br><br>            let layout: AnyLayout = isGrid ? AnyLayout(HStackLayout()) : AnyLayout(VStackLayout())<br><br>            layout {<br>                ForEach(1..&lt;5) { i in<br>                    RoundedRectangle(cornerRadius: 10)<br>                        .fill(Color.blue)<br>                        .frame(width: 80, height: 80)<br>                        .overlay(Text(&quot;\(i)&quot;).foregroundColor(.white))<br>                }<br>            }<br>            .animation(.easeInOut, value: isGrid)<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ND_fmehbjtez1TJ3LK0Vw.png" /><figcaption>1. VStackLayout 2. HStackLayout</figcaption></figure><h3>🌟 Real-World: Adaptive Product Card Layout</h3><pre>struct Product: Identifiable {<br>    let id = UUID()<br>    let title: String<br>    let subtitle: String<br>    let image: String<br>}<br><br>struct ProductCard: View {<br>    var product: Product<br>    var isCompact: Bool<br><br>    var body: some View {<br>        let layout = isCompact ? AnyLayout(VStackLayout(alignment: .leading)) :<br>                                 AnyLayout(HStackLayout(alignment: .center))<br><br>        layout {<br>            Image(systemName: product.image)<br>                .resizable()<br>                .scaledToFit()<br>                .frame(width: 80, height: 80)<br>                .background(Color.gray.opacity(0.1))<br>                .clipShape(Circle())<br><br>            VStack(alignment: .leading) {<br>                Text(product.title).font(.headline)<br>                Text(product.subtitle).font(.subheadline).foregroundColor(.secondary)<br>            }<br>        }<br>        .padding()<br>        .background(RoundedRectangle(cornerRadius: 16).fill(Color.white).shadow(radius: 4))<br>    }<br>}</pre><pre>struct ProductListView: View {<br>    @Environment(\.horizontalSizeClass) var sizeClass<br>    let products = [<br>        Product(title: &quot;AirPods&quot;, subtitle: &quot;Wireless Earbuds&quot;, image: &quot;earbuds&quot;),<br>        Product(title: &quot;iPhone&quot;, subtitle: &quot;Smartphone&quot;, image: &quot;iphone&quot;)<br>    ]<br><br>    var body: some View {<br>        ScrollView {<br>            ForEach(products) { product in<br>                ProductCard(product: product, isCompact: sizeClass == .compact)<br>                    .padding(.horizontal)<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xqFlGGZAqsYCsV9c12cRA.png" /></figure><h3>🧠 Bonus: Works with Custom Layouts Too</h3><pre>let layout = isFancyMode ? AnyLayout(MyCustomMasonryLayout()) : AnyLayout(VStackLayout())</pre><p>As long as your custom layout conforms to Layout, you can plug it into AnyLayout like any native container.</p><h3>🔹 TL;DR</h3><p><strong>SwiftUI’s </strong><strong>AnyLayout at a Glance:</strong></p><ul><li>✅ <strong>One-line layout switching</strong> between VStack, HStack, and custom layouts</li><li>♻️ <strong>Removes layout duplication</strong> by centralizing logic in a type-erased container</li><li>🧱 <strong>Composable</strong> with built-in or custom Layout conforming structures</li><li>📱 <strong>Responsive-ready</strong> for size class, orientation, and dynamic UI conditions</li><li>🧠 <strong>Cleaner, scalable code</strong> for developers building adaptive interfaces</li></ul><h3>🌐 Download Full Sample Project</h3><p><a href="https://github.com/sagar-vaholiya/AnyLayoutDemo/archive/refs/heads/main.zip">Download Demo Project (ZIP)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f46d6ab70310" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>