<?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 Sadık Çoban on Medium]]></title>
        <description><![CDATA[Stories by Sadık Çoban on Medium]]></description>
        <link>https://medium.com/@sadikcoban?source=rss-1c3ac955680e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Sadık Çoban on Medium</title>
            <link>https://medium.com/@sadikcoban?source=rss-1c3ac955680e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:40:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sadikcoban/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[Modern SwiftUI Architecture: Building Scalable Listing Modules]]></title>
            <link>https://medium.com/getir/modern-swiftui-architecture-building-scalable-listing-modules-e04e1e0bbd68?source=rss-1c3ac955680e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e04e1e0bbd68</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sadık Çoban]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 12:28:21 GMT</pubDate>
            <atom:updated>2026-08-12T12:28:21.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gW2bxNiFaGhAfwweYCMRw.png" /></figure><h4>A practical guide to rewriting a heavy, data-dense listing experience in SwiftUI when you can’t drop iOS 15 support — and how to elegantly adopt iOS 17, 18 and 26 APIs along the way.</h4><p>Many teams are migrating existing UIKit screens to SwiftUI to establish a single UI paradigm, simplify state management, and accelerate feature development. It is the natural evolution of iOS development. But the real challenge emerges when tackling a <strong>large, existing module</strong> burdened with numerous screens, heavy lists, and strict deployment constraints — in our case, an <strong>iOS 15 minimum target</strong>.</p><h4>Where We Started</h4><p>Our legacy version of this screen was a single, several-thousand-line UIKit view controller that had grown organically over years of category-specific hacks. Product card layout was duplicated in three or four slightly different flavors across the codebase, so a single design tweak meant hunting down every copy and hoping none of them drifted further apart. Scroll-to-section jumps were driven by manual contentOffset math that broke the moment a banner or promo row changed height. And because everything lived behind one delegate/data-source pair, adding a widget type or tweaking prefetching risked regressing an entirely unrelated part of the screen. On top of all that, cold time-to-interactive on this browsing screen had crept past two seconds, which was directly hurting conversion — this is the problem the rewrite ultimately had to solve.</p><p>Supporting iOS 15 as our floor meant we couldn’t just reach for Apple’s shiny new scroll or layout APIs to handle our core behaviors. We had to architect patterns that functioned flawlessly on iOS 15, while establishing a foundation that could optionally improve on newer OS versions.</p><h4>Why This Architecture</h4><p>Before settling on the approach below, we weighed a couple of alternatives. Optimizing the existing UIKit screen (diffable data sources, tighter cell reuse) would have chipped away at the performance numbers, but it wouldn’t have touched the duplicated cards or the fragile scroll math, and it kept us on a second UI paradigm the rest of the app was actively moving away from. A SwiftUI rewrite built around iOS 16+ conveniences like `scrollPosition(id:)` was tempting on paper, but it was a non-starter against our iOS 15 floor. What we landed on instead — composable building blocks, `List`-driven laziness, and preference-based visibility tracking — let us solve both problems at once: it behaved correctly on iOS 15 from day one, and it left clean seams to swap in native iOS 17/18 APIs later without a second rewrite.</p><h4>What’s Ahead</h4><p>This article details how we approached the SwiftUI migration for a highly complex product-listing experience. We are talking about deep category browsers, subcategory pickers, sectioned lists rendering thousands of items, precise scroll-to-section mechanics, and keeping an “active” subcategory chip perfectly in sync with the user’s scroll position. The payoff was measurable: across two months of production A/B data, the screen’s median time-to-interactive dropped from <strong>2.27 s to 479 ms</strong> — we’ll break down the numbers at the end of the article.</p><p>Below, we’ll explore how we built <strong>reusable components</strong>, implemented <strong>lazy listing</strong>, mastered <strong>scroll tracking</strong>, and handled <strong>programmatic scrolling</strong>, finishing with a breakdown of what iOS 17, 18 and 26 bring to the table.</p><h3>The Foundation: Managing Complexity with Basic Building Blocks</h3><p>If you want to survive a migration of this scale, you cannot afford to duplicate UI logic. To make these complex listing pages manageable, we needed a single source of truth for layout and behavior, allowing screens to be reused in various contexts (like a full-screen category browser, a standalone product list, or a view embedded deep within another flow).</p><p>To achieve this, we stripped our UI down to a core set of <strong>basic building blocks</strong>. By hyper-focusing on a few atomic, highly reusable components, we could compose them upwards to build our most complex screens.</p><p>Two of the most critical foundational blocks we built were our standard <strong>Product Card</strong> and our <strong>Horizontal Product List View</strong>.</p><h3>The Product Card</h3><p>The product card is arguably the most repeated view in any e-commerce application. Because our migration required us to support mixed layouts — specifically standard multi-column grids alongside full-width “wide” promotional items — our base card needed to be highly adaptable without devolving into a massive, tangled view.</p><p>To achieve this, we established a strict separation of concerns. The data itself is isolated in a ProductCardEntity, while all layout instructions are passed via a ProductCardConfiguration.</p><p>Depending on the ProductDisplayType, the card shifts its image dimensions and text alignment.</p><p>Below is a simplified mock of our Product Card. While it doesn’t include every production-level detail — like action handling or advanced styling — it perfectly highlights the core structural pattern we relied on.</p><pre>struct ProductCardView: View {<br>    let entity: ProductCardEntity<br>    let configuration: ProductCardConfiguration<br><br>    var imageHeight: CGFloat {<br>        switch configuration.displayType {<br>        case .square:<br>            return configuration.width<br>        case .wide:<br>            return 150<br>        }<br>    }<br><br>    var alignment: HorizontalAlignment {<br>        switch configuration.displayType {<br>        case .square:<br>            return .leading<br>        case .wide:<br>            return .center<br>        }<br>    }<br><br>    var body: some View {<br>        VStack(<br>            alignment: alignment,<br>            spacing: 4<br>        ) {<br>            AsyncImage(url: .init(string: entity.imageURL)) { phase in<br>                switch phase {<br>                case .empty:<br>                    placeholderImage<br>                case .success(let image):<br>                    image<br>                        .resizable()<br>                        .frame(width: configuration.width, height: imageHeight)<br>                case .failure:<br>                    placeholderImage<br>                @unknown default:<br>                    EmptyView()<br>                }<br>            }<br>            Text(entity.title)<br><br>            Text(entity.price)<br>        }<br>    }<br><br>    private var placeholderImage: some View {<br>        Color.gray<br>            .frame(width: configuration.width, height: imageHeight)<br>    }<br>}<br><br>struct ProductCardEntity: Identifiable {<br>    let id: String<br>    let title: String<br>    let price: String<br>    let imageURL: String<br>}<br><br>enum ProductDisplayType {<br>    case square<br>    case wide<br>}<br><br>struct ProductCardConfiguration {<br>    let width: CGFloat<br>    let displayType: ProductDisplayType<br>}</pre><p>By injecting the ProductCardConfiguration at the row level, our parent views dictate the layout geometry, keeping ProductCardView unaware of its environment.</p><h4>Horizontal Product List View</h4><p>With our atomic ProductCardView established, we needed a way to display these items in a horizontal, scrollable carousel. This is where our reusable component strategy truly began to pay off.</p><p>Instead of hardcoding a specific carousel for “Recommended Products” and another for “Recently Viewed,” we built a highly configurable wrapper. Here is a look at the code:</p><pre>struct HorizontalProductListViewConfiguration {<br>    /// Defines the width of the product card. Defaults to `92`<br>    let productWidth: CGFloat<br><br>    /// Defines the horizontal distance between product cards. Defaults to `16`<br>    let productSpacing: CGFloat<br><br>    init(<br>        productWidth: CGFloat = 92,<br>        productSpacing: CGFloat = 16<br>    ) {<br>        self.productWidth = productWidth<br>        self.productSpacing = productSpacing<br>    }<br>}<br><br>struct HorizontalProductListView&lt;HeaderView: View&gt;: View {<br>    let configuration: HorizontalProductListViewConfiguration<br>    let products: [ProductCardEntity]<br>    let headerView: HeaderView<br><br>    init(<br>        configuration: HorizontalProductListViewConfiguration = .init(),<br>        products: [ProductCardEntity],<br>        headerView: HeaderView = EmptyView()<br>    ) {<br>        self.configuration = configuration<br>        self.products = products<br>        self.headerView = headerView<br>    }<br><br>    var body: some View {<br>        VStack(alignment: .leading, spacing: .zero) {<br>            headerView<br>            productList<br>                // Critical for embedding inside vertical lists<br>                .fixedSize(horizontal: false, vertical: true) <br>        }<br>    }<br><br>    private var productList: some View {<br>        ScrollView(.horizontal) {<br>            LazyHStack(spacing: configuration.productSpacing) {<br>                ForEach(products) { entity in<br>                    ProductCardView(<br>                        entity: entity,<br>                        configuration: ProductCardConfiguration(<br>                            width: configuration.productWidth,<br>                            displayType: .square<br>                        )<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>There are three architectural choices here that made our migration much smoother:</p><ol><li><strong>Generic Headers:</strong> By making HeaderView a generic parameter (defaulting to EmptyView), this component can be placed anywhere. It can take a complex custom title view with an &quot;Access All&quot; button, or it can be completely headless.</li><li><strong>Inversion of Control:</strong> Notice how the HorizontalProductListView dictates the configuration of the ProductCardView (forcing it into a .square display type). The card itself remains purely foundational, while the parent container drives the layout.</li><li><strong>The </strong>.fixedSize<strong> Trick:</strong> Embedding a horizontal ScrollView inside a larger vertical scrolling container is a notorious source of layout bugs in early SwiftUI. By applying .fixedSize(horizontal: false, vertical: true) to the productList, we force the scroll view to wrap its content tightly on the vertical axis, preventing it from collapsing or expanding unpredictably.</li></ol><p>By layering these basic building blocks, we created a robust toolkit. Whether we needed a standalone horizontal carousel or a complex grid embedded within a massive category browser, we were simply reusing and configuring these same views.</p><h4>Listing that many items lazily (Without Melting the Device)</h4><p>With our base components locked in, we faced our biggest hurdle: rendering the massive vertical category browser. We were dealing with hundreds or even thousands of products, grouped into distinct sections.</p><p>We had two absolute requirements:</p><ol><li><strong>Aggressive lazy loading</strong> to keep the memory footprint low.</li><li><strong>Precision scrolling</strong> to jump directly to a specific section when a user tapped a subcategory chip.</li></ol><p>These requirements quickly forced us into a corner, and we had to throw away several iterations before finding the right architecture.</p><h4>What Didn’t Work</h4><p>If you have built complex lists in SwiftUI, you have probably tried these approaches — and felt the same pain we did:</p><ul><li>The Massive<strong> </strong>ScrollView<strong>:</strong> We initially dumped everything into a single ScrollView and tried using ScrollViewReader.scrollTo(id) to jump between sections. It was incredibly unreliable on iOS 15. The scroll view would frequently land on the wrong section or calculate the final offset incorrectly.</li><li>The<strong> </strong>VStack<strong> </strong>of<strong> </strong>LazyVGrids<strong>:</strong> Next, we tried wrapping each section in its own LazyVGrid and stacking them all inside a standard VStack. The result? Astronomical memory usage. SwiftUI’s lazy rendering simply did not combine well in this nested setup, and we completely lost the benefits of laziness.</li><li>The Non-Lazy<strong> </strong>Grid<strong>:</strong> Using a non-lazy Grid (or standard VStacks) was immediately ruled out. Instantiating thousands of cells upfront is a surefire way to crash an app. We needed laziness at <em>some</em> level of granularity.</li></ul><h4>The Solution: A List with Row-Based Sections</h4><p>To get the reliability of scrollTo alongside predictable memory management, we combined a top-level List with manually calculated <strong>row-based layouts</strong>.</p><p>Instead of a single scrolling canvas of individual products, our List consists of <strong>one row per section</strong>. Each list row represents an entire block of products (e.g., &quot;Sneakers&quot; or &quot;Jackets&quot;), complete with its own optional banner and title.</p><p>Inside those section rows, we completely avoid LazyVGrid. Instead, we map our products into a precomputed row-based layout:</p><ol><li><strong>Precompute the Rows:</strong> Before rendering, we chunk our 1D array of products into a 2D array of rows. For example, row 1 might contain three standard products, while row 2 contains a single “wide” promotional item that spans the full width.</li><li><strong>Render with </strong>HStack<strong>:</strong> In the view layer, we iterate over these precomputed chunks using ForEach(rows). For each chunk, we render a simple HStack containing our reusable ProductCardViews with carefully calculated, fixed widths.</li></ol><p>This architecture gave us everything we needed:</p><ul><li>Bulletproof lazy section loading directly from the List.</li><li>Flawless support for mixed layouts (like injecting a full-width promotional card in the middle of a 2-column grid).</li><li>A flat, highly predictable memory footprint without stacking volatile LazyVGrids.</li></ul><h3>Composing the Views: From Building Blocks to Full Screens</h3><p>With our row-based architecture locked in, we could start composing our views upward — building from a low-level sectioned grid, through a single-category detail screen, all the way up to a full multi-category browser with horizontal paging.</p><h4>SectionedProductListView — The Core Grid</h4><p>The SectionedProductListView is the workhorse of our entire listing module. Its sole responsibility is to take a single section’s data and render a grid of products using our precomputed row-based layout. It does not manage scrolling, coordinate spaces, or navigation — it simply converts a section entity into a fully laid-out block of product cards.</p><p>Here is a simplified version of our implementation:</p><pre>struct SectionedProductListView: View {<br>    let entity: SectionedProductListViewEntity<br><br>    var body: some View {<br>        titleView<br>        productList<br>    }<br><br>    @ViewBuilder<br>    private var titleView: some View {<br>        if let title = entity.title {<br>            Text(title)<br>                .font(.headline)<br>                .padding(.horizontal, 16)<br>        }<br>    }<br><br>    private var productList: some View {<br>        ForEach(entity.rows) { row in<br>            HStack(alignment: .top, spacing: entity.columnSpacing) {<br>                ForEach(row.items) { item in<br>                    ProductCardView(<br>                        entity: item.product,<br>                        configuration: ProductCardConfiguration(<br>                            width: entity.itemWidth(for: item.product.displayType),<br>                            displayType: item.product.displayType<br>                        )<br>                    )<br>                    .frame(width: entity.itemWidth(for: item.product.displayType))<br>                }<br>            }<br>            .frame(maxWidth: .infinity, alignment: .leading)<br>            .padding(.vertical, entity.rowSpacing / 2)<br>            .padding(.horizontal, entity.edgeInsets.leading)<br>        }<br>    }<br>}</pre><p>There are a few things worth calling out:</p><p><strong>No Scroll Container:</strong> SectionedProductListView does not wrap its content in a ScrollView or List. It is designed to be embedded inside a parent scroll container. This is absolutely critical — if it managed its own scrolling, we would lose the lazy loading we fought so hard to achieve.</p><p><strong>ForEach Over Precomputed Rows:</strong> We iterate over entity.rows — an array of GridItemRow values that were precomputed before rendering. Each row already knows exactly which products it contains and how many columns it spans.</p><p>This view is intentionally simple. It has no awareness of categories, subcategories, or scroll positions. That simplicity is what allows it to be reused everywhere — in a standalone product list, inside a category detail screen, or nested within a multi-category browser.</p><h4>CategoryProductsView — The Scrollable Product List Engine</h4><p>The CategoryProductsView is the bridge between our raw grid component and our screen-level containers. It takes ownership of the scroll container, the subcategory picker bar, and the programmatic scroll-to-section behavior. Neither CategoryDetailView nor CategoryBrowserView manage scrolling directly — they both delegate to this view.</p><p>Here is a simplified version:</p><pre>struct CategoryProductsView&lt;ViewModel: CategoryProductsViewModelling&gt;: View {<br>    @ObservedObject var viewModel: ViewModel<br><br>    var body: some View {<br>        VStack(spacing: .zero) {<br>            subcategoryPicker<br>            productScrollView<br>        }<br>    }<br><br>    private var subcategoryPicker: some View {<br>        ScrollView(.horizontal, showsIndicators: false) {<br>            HStack(spacing: 8) {<br>                ForEach(viewModel.subcategories) { subcategory in<br>                    ChipView(<br>                        title: subcategory.title,<br>                        isSelected: subcategory.id == viewModel.activeSubcategoryId<br>                    )<br>                    .onTapGesture {<br>                        viewModel.onSubcategoryTapped(subcategory)<br>                    }<br>                }<br>            }<br>            .padding(.horizontal, 16)<br>        }<br>    }<br><br>    private var productScrollView: some View {<br>        ScrollViewReader { proxy in<br>            List {<br>                ForEach(viewModel.productListSections) { section in<br>                    SectionedProductListView(entity: section)<br>                        .fixedSize(horizontal: false, vertical: true)<br>                        .listRowSeparator(.hidden)<br>                        .listRowInsets(.init())<br>                        .id(section.id)<br>                }<br>            }<br>            .listStyle(.plain)<br>            .onReceive(viewModel.scrollTargetPublisher) { sectionId in<br>                proxy.scrollTo(sectionId, anchor: .top)<br>            }<br>        }<br>    }<br>}</pre><p>A few important design choices here:</p><p><strong>List as Scroll Container:</strong> The CategoryProductsView wraps our SectionedProductListView instances inside a List. Each section becomes a single list row. Because List is inherently lazy, only the sections visible on screen are ever rendered. This is what prevents our memory from exploding when a category contains dozens of sections with thousands of products.</p><p><strong>ScrollViewReader for Programmatic Navigation:</strong> When a user taps a subcategory chip, we publish the target section’s identifier through scrollTargetPublisher. The ScrollViewReader picks this up and calls proxy.scrollTo(sectionId, anchor: .top), which reliably snaps the list to the correct section. This was the key advantage of choosing List over a raw ScrollView — on iOS 15, scrollTo with List proved far more reliable than scrollTo with ScrollView.</p><p><strong>The .fixedSize Modifier:</strong> We apply .fixedSize(horizontal: false, vertical: true) to each SectionedProductListView. Without this, the List would collapse each row to a default height rather than sizing it to fit the entire section&#39;s grid content.</p><h4>CategoryDetailView — A Single Category Screen</h4><p>The CategoryDetailView represents a single-category product listing. It is a thin, state-driven container that manages lifecycle events and view state transitions, then delegates all layout work to CategoryProductsView.</p><p>Here is the simplified structure:</p><pre>struct CategoryDetailView&lt;ViewModel: CategoryDetailViewModelling&gt;: View {<br>    @ObservedObject var viewModel: ViewModel<br><br>    var body: some View {<br>        content<br>            .onAppear(perform: viewModel.viewDidAppear)<br>            .onDisappear(perform: viewModel.viewDidDisappear)<br>    }<br><br>    @ViewBuilder<br>    private var content: some View {<br>        switch viewModel.viewState {<br>        case .empty:<br>            EmptyView()<br>        case .loading:<br>            SkeletonView()<br>        case .loaded(let entity):<br>            CategoryProductsView(viewModel: entity.viewModel)<br>        }<br>    }<br>}</pre><p><strong>State-Driven Container:</strong> CategoryDetailView switches between empty, loading, and loaded states. It does not contain any layout or scrolling logic — that lives entirely in CategoryProductsView. This separation means we can reuse the exact same product listing behavior in completely different screen contexts without duplicating a single line of scroll or picker code.</p><h4>CategoryBrowserView — Multi-Category Horizontal Paging</h4><p>The CategoryBrowserView is the most complex screen in our module. It allows users to browse multiple top-level categories by swiping horizontally, with each page being a full CategoryProductsView (subcategory picker + sectioned product list).</p><p>Here is a simplified view of the implementation:</p><pre>struct CategoryBrowserView&lt;ViewModel: CategoryBrowserViewModelling&gt;: View {<br>    @StateObject var viewModel: ViewModel<br><br>    var body: some View {<br>        VStack(spacing: .zero) {<br>            categoryPickerView<br>            productListView<br>        }<br>    }<br><br>    private var categoryPickerView: some View {<br>        ScrollView(.horizontal, showsIndicators: false) {<br>            HStack(spacing: .zero) {<br>                ForEach(viewModel.categories) { category in<br>                    TabButton(<br>                        title: category.title,<br>                        isSelected: category.id == viewModel.activeCategoryId<br>                    )<br>                    .onTapGesture {<br>                        viewModel.didSelectCategory(category)<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    @ViewBuilder<br>    private var productListView: some View {<br>        if #available(iOS 17.0, *) {<br>            modernProductListView<br>        } else {<br>            legacyProductListView<br>        }<br>    }<br><br>    @available(iOS 17.0, *)<br>    private var modernProductListView: some View {<br>        ScrollView(.horizontal, showsIndicators: false) {<br>            LazyHStack(spacing: .zero) {<br>                ForEach(viewModel.categories) { category in<br>                    categoryPageView(for: category.id)<br>                        .containerRelativeFrame(.horizontal, count: 1, spacing: .zero)<br>                        .id(category.id)<br>                }<br>            }<br>            .scrollTargetLayout()<br>        }<br>        .scrollTargetBehavior(.paging)<br>        .scrollPosition(id: $viewModel.scrollPosition)<br>    }<br><br>    private var legacyProductListView: some View {<br>        CategoryProductsView(<br>            viewModel: viewModel.activeViewModel<br>        )<br>        .id(viewModel.activeCategoryId)<br>        .gesture(viewModel.swipeGesture)<br>    }<br><br>    @ViewBuilder<br>    private func categoryPageView(for categoryId: UUID) -&gt; some View {<br>        if let productsViewModel = viewModel.viewModels[categoryId] {<br>            CategoryProductsView(viewModel: productsViewModel)<br>        } else {<br>            SkeletonView()<br>        }<br>    }<br>}</pre><p>This is where the differences between iOS versions become most visible:</p><p><strong>iOS 17+ Paging:</strong> On iOS 17 and later, we use a horizontal ScrollView with .scrollTargetBehavior(.paging) and .containerRelativeFrame to get native, gesture-driven page-snapping. Each page is a full CategoryProductsView rendered lazily inside a LazyHStack. The .scrollPosition binding keeps our top-level category picker perfectly in sync with the user&#39;s swipe position.</p><p><strong>iOS 15/16 Fallback:</strong> On older versions, none of those APIs exist. Instead of fighting a ScrollView into behaving like a pager, we render only the active category’s CategoryProductsView and swap it out when the user taps a different category tab or performs a custom swipe gesture. We attach the category’s identifier via .id(), so SwiftUI treats each swap as a fresh view, avoiding stale state.</p><p><strong>Lazy ViewModel Resolution:</strong> Notice how categoryPageView(for:) looks up the CategoryProductsViewModel from a dictionary (viewModel.viewModels[categoryId]). Not all categories are loaded at once — the view models are created on-demand as the user navigates. If a category hasn&#39;t been fetched yet, we show a skeleton placeholder. This keeps the initial load fast and the memory footprint proportional to what the user has actually browsed.</p><p>The composition pattern is now fully visible: CategoryBrowserView pages between CategoryProductsView instances, each of which wraps a List of SectionedProductListView sections, each of which renders precomputed rows of ProductCardView items. Every layer has a single, well-defined responsibility, and the lazy loading guarantees flow naturally from the outermost scroll container down to the individual product cells.</p><h4>Keeping Subcategory Chips in Sync with the Scroll Position</h4><p>At this point we had a working product list — sections loaded lazily, programmatic scroll-to-section worked reliably, and all our building blocks composed cleanly. But there was one critical UX requirement left: when a user manually scrolls through the list, the active subcategory chip at the top must update automatically to reflect whichever section is currently visible.</p><p>This is a deceptively hard problem. SwiftUI on iOS 15 provides no built-in “visible items” callback. There is no onVisibleItemsChange modifier, no scroll offset reader, and no intersection observer equivalent. We had to build the entire mechanism ourselves using SwiftUI&#39;s preference system.</p><h4>The Core Idea: Anchor Preferences as an Intersection Observer</h4><p>Our approach has three layers:</p><ol><li>Each section reports its geometric bounds upward through a preference key.</li><li>A parent modifier collects all reported bounds and resolves them against the scroll view’s coordinate space.</li><li>When the set of visible sections changes, we notify the view model, which updates the active chip.</li></ol><h4>Step 1 — Reporting Bounds with a Preference Key</h4><p>First, we define a preference key that collects a dictionary of section identifiers mapped to their anchor rectangles:</p><pre>struct VisibleItemsPreferenceKey&lt;ID: Hashable&gt;: PreferenceKey {<br>    typealias Value = [ID: Anchor&lt;CGRect&gt;]<br><br>    static var defaultValue: Value { [:] }<br><br>    static func reduce(value: inout Value, nextValue: () -&gt; Value) {<br>        value.merge(nextValue(), uniquingKeysWith: { $1 })<br>    }<br>}</pre><p>Each section in our list attaches its bounds using a lightweight view modifier:</p><pre>extension View {<br>    func trackVisibility&lt;ID: Hashable&gt;(for id: ID) -&gt; some View {<br>        anchorPreference(<br>            key: VisibleItemsPreferenceKey&lt;ID&gt;.self,<br>            value: .bounds<br>        ) { anchor in<br>            [id: anchor]<br>        }<br>    }<br>}</pre><p>This is the “broadcast” side. Every section simply says: “Here is my identifier, and here are my bounds.” It has no awareness of who is listening or what will be done with this information.</p><h4>Step 2 — Resolving Anchors and Detecting Visibility</h4><p>On the receiving side, we attach a modifier to the scroll view that reads all collected anchors and resolves them against the scroll view’s own frame using a GeometryReader:</p><pre>extension View {<br>    func onVisibleItemsChange&lt;ID: Hashable&gt;(<br>        coordinateSpaceName: String,<br>        perform: @escaping (Set&lt;ID&gt;) -&gt; Void<br>    ) -&gt; some View {<br>        backgroundPreferenceValue(VisibleItemsPreferenceKey&lt;ID&gt;.self) { anchors in<br>            GeometryReader { geometry in<br>                let scrollFrame = geometry.frame(in: .named(coordinateSpaceName))<br>                let visibleIds = Set(<br>                    anchors.compactMap { id, anchor in<br>                        let itemFrame = geometry[anchor]<br>                        return scrollFrame.intersects(itemFrame) ? id : nil<br>                    }<br>                )<br>                Color.clear<br>                    .onChange(of: visibleIds) { newValue in<br>                        perform(newValue)<br>                    }<br>                    .onAppear {<br>                        perform(visibleIds)<br>                    }<br>            }<br>        }<br>    }<br>}</pre><p>The key insight here is that Anchor values are opaque — they cannot be resolved into concrete CGRect values without a GeometryProxy. By using backgroundPreferenceValue, we get access to both the collected anchors and a geometry proxy in the same context, allowing us to resolve every section’s frame and test it against the scroll view’s visible rect using a simple intersects check.</p><h4>Step 3 — Wiring It Into the Product List</h4><p>In our CategoryProductsView, the integration looks like this:</p><pre>private var productScrollView: some View {<br>    ScrollViewReader { proxy in<br>        List {<br>            ForEach(viewModel.productListSections) { section in<br>                SectionedProductListView(entity: section)<br>                    .trackVisibility(for: section.id)<br>                    .id(section.id)<br>            }<br>        }<br>        .onReceive(viewModel.scrollTargetPublisher) { sectionId in<br>            proxy.scrollTo(sectionId, anchor: .top)<br>        }<br>        .onVisibleItemsChange(<br>            coordinateSpaceName: viewModel.coordinateSpaceName,<br>            perform: viewModel.onVisibleItemsChanged<br>        )<br>    }<br>    .coordinateSpace(name: viewModel.coordinateSpaceName)<br>}</pre><p>Each section is tagged with .trackVisibility(for: section.id). The scroll view&#39;s parent is given a named coordinate space, and the .onVisibleItemsChange modifier is attached to the List to collect and resolve all anchors within that space. Whenever the visible set changes — because the user scrolled — the view model is notified.</p><h4>Step 4 — Updating the Active Chip</h4><p>Inside the view model, the logic for selecting the active chip is straightforward:</p><pre>func onVisibleItemsChanged(_ ids: Set&lt;UUID&gt;) {<br>    guard !isScrollingViaPickerSelection,<br>          !ids.isEmpty else { return }<br><br>    let pickerItems = config.subCategoryPickerItems<br><br>    // If the bottom spacer is visible, snap to the last chip<br>    if ids.contains(bottomSpacerViewId),<br>       let lastItem = pickerItems.last {<br>        activePickerItem = lastItem<br>        return<br>    }<br><br>    // Build an index lookup for ordering<br>    let indexMap = Dictionary(<br>        uniqueKeysWithValues: pickerItems.enumerated().map { ($1.id, $0) }<br>    )<br><br>    // Sort visible IDs by their picker order, pick the first<br>    let sortedIds = ids.sorted {<br>        (indexMap[$0] ?? .max) &lt; (indexMap[$1] ?? .max)<br>    }<br><br>    if let firstId = sortedIds.first,<br>       let item = pickerItems.first(where: { $0.id == firstId }) {<br>        activePickerItem = item<br>    }<br>}</pre><p>The logic: take all currently visible section IDs, sort them by their original order in the picker, and select the first one as the active chip. There is one special case — if the user has scrolled all the way to the bottom (the bottom spacer view is visible), we force-select the last chip regardless, because the final section may only be partially visible.</p><h4>The Guard Against Feedback Loops</h4><p>There is a subtle but critical detail: the isScrollingViaPickerSelection flag. Without it, tapping a chip would trigger a programmatic scroll, which would change the visible items, which would update the active chip, which could trigger another scroll — a classic feedback loop.</p><p>When a user taps a chip, we set this flag to true and send the scroll target:</p><pre>func onSubcategoryTapped(_ item: SubCategoryPickerItem) {<br>    isScrollingViaPickerSelection = true<br>    scrollTargetSubject.send(item.id)<br><br>    DispatchQueue.main.asyncAfter(deadline: .now() + Constants.scrollAnimationDuration) {<br>        self.isScrollingViaPickerSelection = false<br>    }<br>}</pre><p>While the flag is true, all incoming visibility updates are silently ignored. After the scroll animation settles (roughly 0.3 seconds), we re-enable visibility tracking. This creates a clean one-way data flow: either the user is scrolling and the chips follow, or the user tapped a chip and the list follows — never both at once.</p><h3>Further Improvement: Smart Category Prefetching with Swift Actors</h3><p>When a user lands on the CategoryBrowserView, we do not fetch all categories upfront — that would be wasteful. But we also cannot wait until a user swipes to a new category to start loading it, because the resulting delay would feel sluggish. We needed a middle ground: fetch the current category immediately, and silently prefetch its immediate neighbors.</p><p>We implemented this using a Swift actor called CategoryBrowserDataManager. The actor owns all in-flight network tasks and cached responses, giving us thread-safe data management without manual locking:</p><pre>protocol CategoryBrowserDataManaging: Actor {<br>    func fetchCategoryDataIfNeeded(id: String) async -&gt; CategoryProductsResponse?<br>    func cancelFetch(for id: String)<br>}<br><br>actor CategoryBrowserDataManager: CategoryBrowserDataManaging {<br>    private var tasks: [String: Task&lt;CategoryProductsResponse?, Never&gt;] = [:]<br>    private var storage: [String: CategoryProductsResponse?] = [:]<br>    private let repository: CategoryRepositoryProtocol<br><br>    func fetchCategoryDataIfNeeded(id: String) async -&gt; CategoryProductsResponse? {<br>        // Return cached data immediately if available<br>        if let cached = storage[id] {<br>            return cached<br>        }<br>        // Await in-flight task if one already exists<br>        if let existing = tasks[id], !existing.isCancelled {<br>            return await existing.value<br>        }<br>        // Otherwise, create a new fetch task<br>        let task = Task {<br>            let result = await repository.getCategoryProducts(with: id)<br>            switch result {<br>            case .success(let data):<br>                storage[id] = data<br>                return data<br>            case .failure:<br>                tasks[id] = nil<br>                return nil as CategoryProductsResponse?<br>            }<br>        }<br>        tasks[id] = task<br>        return await task.value<br>    }<br><br>    func cancelFetch(for id: String) {<br>        tasks[id]?.cancel()<br>        tasks[id] = nil<br>    }<br>}</pre><p>There are three behaviors baked into this actor that are worth highlighting:</p><p><strong>Request Deduplication: </strong>If two callers request the same category simultaneously (for example, a prefetch and a user-initiated swipe arriving at the same time), the second caller simply awaits the already-in-flight task instead of firing a duplicate network request.</p><p><strong>Transparent Caching:</strong> Once a response is stored, subsequent calls return instantly from the cache. If the caller needs to know whether the data came from the network or from memory, the actor could report it too.</p><p><strong>Cooperative Cancellation:</strong> When a user scrolls away, we call cancelFetch for categories that are no longer relevant. The actor cancels the in-flight task and cleans up the reference, preventing wasted bandwidth and stale completions.</p><p>The ViewModel orchestrates the prefetch strategy by maintaining a sliding window of three categories — the current one plus its immediate left and right neighbors:</p><pre>func loadCategoryData(previous: UUID?, current: UUID?) {<br>    let oldRequired = getRequiredIDs(for: previous)<br>    let newRequired = getRequiredIDs(for: current)<br><br>    let toCancel = oldRequired.subtracting(newRequired)<br>    Task {<br>        for id in toCancel {<br>            await dataManager.cancelFetch(for: id)<br>        }<br><br>        var toFetch = newRequired.filter { viewModels[$0] == nil }<br><br>        // Prioritize the current category — fetch it first, sequentially<br>        if let current, toFetch.contains(current) {<br>            if let result = await fetchCategory(uuid: current) {<br>                await appendViewModel(for: current, response: result)<br>            }<br>            toFetch.remove(current)<br>        }<br><br>        // Fetch remaining neighbors concurrently<br>        await withTaskGroup(of: Void.self) { group in<br>            for id in toFetch {<br>                group.addTask { [weak self] in<br>                    guard let self else { return }<br>                    if let result = await self.fetchCategory(uuid: id) {<br>                        await self.appendViewModel(for: id, response: result)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br>private func getRequiredIDs(for centerUUID: UUID?) -&gt; Set&lt;UUID&gt; {<br>    guard let centerUUID,<br>          let items = pickerItems,<br>          let index = items.firstIndex(where: { $0.id == centerUUID })<br>    else { return [] }<br><br>    var ids: Set&lt;UUID&gt; = [centerUUID]<br>    if index &gt; 0 { ids.insert(items[index - 1].id) }<br>    if index &lt; items.count - 1 { ids.insert(items[index + 1].id) }<br>    return ids<br>}</pre><p>The current category is always fetched sequentially first — it must appear on screen as fast as possible. The sibling neighbors are then fetched in parallel via a TaskGroup, because the user should not wait for them.</p><p>This approach is not specific to our use case. Any application that serves paginated, tab-based content where each tab’s data comes from a separate API call can benefit from this pattern: an actor for thread-safe caching and deduplication, a sliding window for prefetch scope, and sequential-then-parallel loading for perceived responsiveness.</p><h4>What iOS 17, 18, and 26 Bring to the Table</h4><p>Throughout this article, we have been building on an iOS 15 baseline: manually tracking visibility with preferences, fighting ScrollView for reliable scrollTo behavior, and simulating horizontal paging without system support. But each subsequent iOS release has introduced APIs that could progressively simplify or replace parts of our architecture.</p><p>Here is a breakdown of what each version unlocks.</p><p><strong>iOS 17: Native Paging and Scroll Position</strong></p><p>iOS 17 was the single biggest quality-of-life jump for our module. It introduced three APIs that directly addressed our pain points:</p><p>.scrollTargetBehavior(.paging) and .containerRelativeFrame These two modifiers gave us native, gesture-driven page-snapping in our CategoryBrowserView. Before iOS 17, we had to render only the active category and swap views on tap or gesture. With these APIs, we could place every category inside a LazyHStack and let the system handle paging physics, deceleration, and snap-to-page behavior. This was the iOS 17 path we showed in our CategoryBrowserView implementation.</p><p>.scrollPosition(id:) This binding gave us a two-way connection between the scroll offset and a state variable. When the user swipes to a new page, the binding updates automatically — no gesture recognizers or manual offset calculations needed. This is what keeps our top-level category picker perfectly in sync.</p><p><strong>iOS 18: Geometry-Aware Scrolling</strong></p><p>iOS 18 introduced a set of APIs that could fundamentally simplify our custom visibility tracking system:</p><p>onScrollGeometryChange This modifier reports changes to the scroll view&#39;s content offset, content size, and visible rect. For our subcategory chip syncing, this could replace the entire anchorPreference + GeometryReader pipeline we built. Instead of each section broadcasting its bounds and a parent resolving intersections, we could read the scroll offset directly and compute which section is visible from the content layout.</p><p>onScrollPhaseChange This tells you whether the scroll view is idle, dragging, decelerating, or animating. We could use this to replace our isScrollingViaPickerSelection flag with something more precise — for example, ignoring visibility updates only during the .animating phase and re-enabling them once the phase returns to .idle, rather than relying on a hardcoded animation duration delay.</p><p>onScrollTargetVisibilityChange This is essentially the system-provided version of our entire visibility tracking mechanism. You mark views with .scrollTargetLayout() and SwiftUI tells you exactly which identifiers are currently visible. On iOS 18+, this single modifier could replace our VisibleItemsPreferenceKey, the trackVisibility modifier, the onVisibleItemsChange modifier, and the GeometryReader resolution logic; collapsing hundreds of lines into one.</p><p><strong>iOS 26: Visual Polish and Liquid Glass</strong></p><p>iOS 26 focuses less on new scroll mechanics and more on visual integration:</p><p>scrollEdgeEffectStyle SwiftUI now automatically applies blur and dimming to content near the edges of scroll views, creating a smooth visual transition under translucent bars. You can customize this per edge using .soft for gradual fading or .hard for sharp cutoffs. For our List-based product grids, this means the content blends naturally under the navigation bar and tab bar without any manual gradient overlays.</p><p>tabBarMinimizeBehavior(.onScrollDown) The tab bar can now automatically minimize when the user scrolls down, giving more screen real estate to product content, a small but meaningful UX win for data-dense listing screens like ours.</p><p>The table below summarizes the progression:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FFugzs%2F4%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FFugzs%2F4%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FFugzs%2Fplain-s.png%3Fv%3D4&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="590" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e8809af215f895c634d388e43e4a52/href">https://medium.com/media/70e8809af215f895c634d388e43e4a52/href</a></iframe><p>The important takeaway is that our iOS 15 architecture does not need to be thrown away. Each new API can be adopted incrementally behind an if #available check, replacing one custom subsystem at a time while keeping the rest of the module untouched. That is exactly how we are approaching it: iOS 17 already replaced our legacy pager, iOS 18 will eventually replace our preference-based visibility tracking, and iOS 26&#39;s visual enhancements come essentially for free.</p><h3>Testing Strategies</h3><p>One of the benefits of our strict separation of concerns is that most of the logic worth testing lives in the ViewModel layer, completely decoupled from SwiftUI rendering.</p><p><strong>Unit Testing the ViewModel</strong></p><p>The CategoryProductsViewModel is the most logic-heavy component in the module. It manages subcategory selection, visible item tracking, scroll target publishing, and section data transformations. Because it is a plain ObservableObject, it can be instantiated and tested without any SwiftUI views:</p><pre>func testVisibleItemsUpdatesActiveChip() {<br>    let subcategories = [<br>        SubCategoryPickerItem(id: milkId, title: &quot;Milk&quot;),<br>        SubCategoryPickerItem(id: cheeseId, title: &quot;Cheese&quot;),<br>        SubCategoryPickerItem(id: yogurtId, title: &quot;Yogurt&quot;),<br>    ]<br>    let viewModel = CategoryProductsViewModel(<br>        config: .mock(subCategoryPickerItems: subcategories),<br>        actions: .default,<br>        subCategories: mockSubCategories,<br>        productListManager: MockProductListManager()<br>    )<br><br>    // Simulate scrolling to where Cheese section is visible<br>    viewModel.onVisibleItemsChanged([cheeseId])<br><br>    XCTAssertEqual(viewModel.activePickerItem?.id, cheeseId)<br>}<br><br>func testPickerTapSuppressesVisibilityUpdates() {<br>    // ...setup...<br>    viewModel.onSubcategoryTapped(yogurtItem)<br><br>    // While scrolling via picker, visibility changes should be ignored<br>    viewModel.onVisibleItemsChanged([milkId])<br><br>    XCTAssertEqual(viewModel.activePickerItem?.id, yogurtId)<br>}</pre><p>The feedback loop guard (isScrollingViaPickerSelection), the bottom spacer edge case, and the sorted-first-visible-wins logic are all pure functions operating on Sets and Arrays — straightforward to test exhaustively.</p><p><strong>Testing the Actor</strong></p><p>The CategoryBrowserDataManager actor is inherently testable because it conforms to a protocol. We inject a mock repository and verify caching, deduplication, and cancellation behavior:</p><pre>func testCachesResponseAfterFirstFetch() async {<br>    let mockRepo = MockCategoryRepository(<br>        response: .success(mockCategoryResponse)<br>    )<br>    let manager = CategoryBrowserDataManager(repository: mockRepo)<br><br>    let (first, firstSource) = await manager.fetchCategoryDataIfNeeded(id: &quot;dairy&quot;)<br>    let (second, secondSource) = await manager.fetchCategoryDataIfNeeded(id: &quot;dairy&quot;)<br><br>    XCTAssertNotNil(first)<br>    XCTAssertEqual(firstSource, .network)<br>    XCTAssertEqual(secondSource, .cache)<br>    XCTAssertEqual(mockRepo.fetchCount, 1) // Only one network call<br>}<br><br>func testCancelPreventsCompletion() async {<br>    let manager = CategoryBrowserDataManager(<br>        repository: MockSlowRepository()<br>    )<br><br>    Task { await manager.fetchCategoryDataIfNeeded(id: &quot;dairy&quot;) }<br>    await manager.cancelFetch(for: &quot;dairy&quot;)<br><br>    // Subsequent fetch should create a new task, not reuse cancelled one<br>    let (result, source) = await manager.fetchCategoryDataIfNeeded(id: &quot;dairy&quot;)<br>    XCTAssertEqual(source, .network)<br>}</pre><p><strong>Snapshot and Integration Testing</strong></p><p>For verifying that view composition is correct — that sections render in the right order, chips appear with the right titles, and the layout does not regress — snapshot tests are invaluable. Because our views accept entity-driven configuration, we can construct deterministic snapshots without a running backend:</p><pre>func testCategoryProductsViewSnapshot() {<br>    let viewModel = CategoryProductsViewModel(<br>        config: .mock(subCategoryPickerItems: mockPickerItems),<br>        actions: .default,<br>        subCategories: mockSubCategories,<br>        productListManager: MockProductListManager()<br>    )<br>    viewModel.productListSections = mockSections<br><br>    let view = CategoryProductsView(viewModel: viewModel)<br>    assertSnapshot(matching: view, as: .image(layout: .device(config: .iPhone13)))<br>}</pre><p><strong>What We Deliberately Do Not Test</strong></p><p>We do not unit-test SwiftUI’s built-in behaviors — that .listStyle(.plain) removes separators, or that ScrollViewReader.scrollTo actually scrolls. These are Apple’s contracts. Our tests focus on our logic: given a set of visible IDs, does the ViewModel select the right chip? Given a picker tap, does it publish the right scroll target? Given a fetch request, does the actor deduplicate correctly?</p><h3>Scalability Through Composition Slots</h3><p>One of the most important long-term benefits of our architecture is that it provides clear injection points for new functionality without modifying existing view code. Over time, we have added banners, recommendation widgets, and walkthrough overlays, all without touching the core product grid logic.</p><p>Our SectionedProductListView provides three distinct composition slots:</p><p><strong>Top of Section, Mini Banners:</strong> Each section can optionally display a horizontal banner carousel above its product grid. The data for this carousel lives inside the SectionedProductListViewEntity and is fetched asynchronously per section. The view conditionally renders a MiniBannersWrapperView when banner data is available:</p><pre>// Inside SectionedProductListView body:<br>miniBannerView   // ← Slot 1: Top of section<br>titleView<br>productList      // ← Contains Slot 2</pre><p>The key optimization here is that MiniBannersWrapperView conforms to Equatable. SwiftUI only re-renders it when the banner content actually changes, not on every parent redraw. This is critical because the parent SectionedProductListView may re-render frequently as the user scrolls and product counts update.</p><p><strong>Row Trailing Views:</strong> The RowTrailingViewProvider closure is called after every single row in the grid. This is where we inject contextual widgets like our “Add Product Recommendation” view, a widget that appears below a specific product’s row to suggest complementary items:</p><pre>// In SectionedProductListView:<br>ForEach(entity.rows) { row in<br>    productListRow(items: row.items)<br>    rowTrailingView(on: row)  // ← Slot 2: After each row<br>}</pre><p>The provider receives both the subcategory ID and the row data, so the caller can conditionally decide whether to render anything. In most cases, the closure returns EmptyView. Only when a specific product in a specific row matches the recommendation target does the widget appear.</p><p><strong>List-Level Composition:</strong> Because each section is a separate List row, adding content between sections is as simple as inserting additional views in the ForEach. For example, our bottom spacer view that triggers the &quot;snap to last chip&quot; behavior is just another List row appended after all sections.</p><p><strong>This slot-based approach has a practical benefit:</strong> when a product manager asks for a new feature say, a survey prompt after the third section, or a sponsored banner between sections, we do not need to refactor the grid. We either extend the entity with new optional data (for section-level content) or extend the trailing view closure’s logic (for row-level content).</p><p>The same pattern scales at the screen level. CategoryProductsView has its own composition slots like the filter toolbar at the top, the List content in the middle, and the bottom spacer at the end. CategoryBrowserView adds another layer with the category picker, the progress bar, and walkthrough overlays. Each layer composes the layer below it without reaching into its internals.</p><h3>Measuring the Impact: Production Results</h3><p>Architecture decisions are easy to debate and hard to prove — so let the production data speak. Because the rewrite shipped behind an A/B flag, the legacy UIKit implementation and the new SwiftUI implementation ran side by side in production, serving randomized user cohorts on the same mix of devices and network conditions.</p><p>Both flows report the same Firebase Performance trace for time-to-interactive (TTI), tagged with an attribute that differs legacy and new listing screens. The trace starts when the user opens the category screen and stops once the data has arrived and the list is rendered and interactive. Over the two-month window, Firebase captured roughly <strong>450K measured sessions</strong> for the new flow alone — a sample large enough that the percentiles below are not statistical noise. Comparing the two implementations is therefore a single attribute filter in the Firebase console — no synthetic benchmarks, no lab conditions.</p><p>Here is what the last two months of production data show:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FXZ2mG%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FXZ2mG%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FXZ2mG%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="153" frameborder="0" scrolling="no"><a href="https://medium.com/media/a46705df3ecc5292f3b9f28ad311db66/href">https://medium.com/media/a46705df3ecc5292f3b9f28ad311db66/href</a></iframe><p>Two things are worth being transparent about. First, this is not a pure “SwiftUI renders faster than UIKit” comparison — no UI framework accounts for a 4.7× swing by itself. The gain comes from the architecture shipping as a whole: the actor-based prefetching means many category opens are served straight from the in-memory cache, the precomputed row layout removes per-cell layout work from the critical path, and the List-based laziness keeps the initial render cost proportional to what is actually on screen.</p><p>Second, the p90 numbers matter more than the p50. The drop from 4.77 s to 1.62 s means the worst experiences — older devices, congested networks — improved the most. That is exactly the population an iOS 15-floor app cares about.</p><h4>What About Memory?</h4><p>A fair question for any SwiftUI rewrite — especially one that deliberately keeps three categories alive at once — is what happened to memory. We profiled both implementations with Instruments (Allocations template) on an iPhone 12, running the same browsing scenario: open a category, scroll to the bottom, jump between subcategories, switch categories.</p><p>The result: heap allocations ended at <strong>~107 MiB on the legacy screen versus ~123 MiB on the new one</strong>. In other words, the new architecture holds the active category <strong>plus both of its prefetched neighbors</strong> in memory for roughly the footprint the old screen spent on a single category. Image buffer memory (IOSurface) actually came out lower on the SwiftUI side — the List-based laziness genuinely releases off-screen content instead of keeping it warm.</p><p>That ~15% heap increase is not an accident; it is the price of the sliding-window prefetching described earlier, and it is exactly the trade we intended to make: a few extra megabytes in exchange for instant neighbor-category switches.</p><h3>Limitations and Potential Improvements</h3><p>No architecture is without trade-offs, and ours is no exception. Here are the areas where we see room for improvement.</p><p><strong>Entity Bloat:</strong> Our SectionedProductListViewEntity has grown significantly. It started as a simple data container, but over time it accumulated closures for every interaction (onPlusTapped, onMinusTapped, onProductTapped, didProductAppear, onBannerItemClick), display flags (shouldDisplayTitle, isBorderEnabled, isPlusButtonActive, displayPriceText), and layout configuration (itemWidthGenerator, gridStyle, edgeInsets). This makes the initializer unwieldy and difficult to read. A cleaner approach would be to split it into separate concerns; a layout configuration struct, an interaction handler protocol, and a pure data model rather than bundling everything into a single entity.</p><p><strong>Precomputed Rows Are Rigid:</strong> Our row-based layout is calculated once before rendering. If the device rotates or the user changes accessibility text sizes, the rows need to be fully recomputed and the sections rebuilt. We handle this, but it introduces a noticeable layout recalculation cost.</p><p><strong>The Hardcoded Scroll Delay:</strong> Our isScrollingViaPickerSelection flag relies on the animation duration delay to prevent feedback loops between chip taps and visibility updates. This is a heuristic, and it occasionally fails if the scroll animation takes longer than expected (due to a large jump or a slow device), visibility tracking re-enables too early and can briefly flicker the active chip. On iOS 18+, replacing this with onScrollPhaseChange (reacting to the .idle phase) would be a definitive fix.</p><p><strong>List Quirks: </strong>Using List as our primary scroll container was the right call for lazy loading and scrollTo reliability, but List carries baggage. It applies default styling (row separators, insets, minimum row heights) that we must explicitly strip away with:</p><ul><li>listRowSeparator(.hidden)</li><li>listRowInsets(.init())</li><li>environment(.defaultMinListRowHeight, 0)</li></ul><p>Missing any of these modifiers causes subtle visual bugs. Additionally, List on iOS 15 does not support .listRowSpacing, so we rely on padding in the SectionedProductListView itself, which can lead to inconsistent spacing if not carefully managed.</p><p><strong>Limited Diffing for Large Sections:</strong> When a section’s product data changes (for example, a product count updates or a new item is added), SwiftUI diffs the entire SectionedProductListView for that section. Because each section can contain dozens of rows and hundreds of products, this diff can be expensive.</p><p>We mitigate this with Equatable conformance on wrapper views like MiniBannersWrapperView, but we have not yet applied the same optimization to the product grid rows themselves. Implementing custom Equatable conformance on GridItemRow or using the id-based identity more aggressively could reduce unnecessary redraws.</p><h3>Conclusion</h3><p>Migrating a large listing module to SwiftUI under an iOS 15 constraint taught us that the right abstractions — composable building blocks, List-driven lazy loading, and preference-based visibility tracking — can carry enormous complexity without becoming complex themselves. The architecture is deliberately simple at every layer, which is exactly what allowed us to add features like horizontal paging, smart prefetching, and contextual widgets without rewriting the foundation.</p><p>The numbers back this up: a 4.7× faster median time-to-interactive in production, achieved while holding three categories in memory for roughly the footprint the old screen spent on one.</p><p>Just as importantly, each iOS release lets us swap one hand-rolled subsystem for a native API — iOS 17 already replaced our legacy pager, iOS 18 will eventually replace our preference-based visibility tracking — progressively simplifying the codebase while the baseline stays solid.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e04e1e0bbd68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getir/modern-swiftui-architecture-building-scalable-listing-modules-e04e1e0bbd68">Modern SwiftUI Architecture: Building Scalable Listing Modules</a> was originally published in <a href="https://medium.com/getir">Getir</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍HMS CORE: What have we done in January 2023?]]></title>
            <link>https://medium.com/huawei-developers/hms-core-what-have-we-done-in-january-2023-b2c62ac75a26?source=rss-1c3ac955680e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2c62ac75a26</guid>
            <category><![CDATA[xamarin]]></category>
            <category><![CDATA[hms-core]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[cordova]]></category>
            <dc:creator><![CDATA[Sadık Çoban]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 12:32:29 GMT</pubDate>
            <atom:updated>2023-02-28T12:32:29.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ZqBIMOY-ORITXWnGP4ONtg.png" /></figure><p>Hello Everyone!</p><p>We are the HMS Core Cross-Platform Plugin team from Turkey! Our Team creates the cross-platform plugins for HMS Core across four different platforms, namely <strong>React Native</strong>, <strong>Cordova</strong>, <strong>Xamarin</strong>, and <strong>Flutter</strong>. We consistently release monthly package updates on <a href="https://www.npmjs.com/~hmscore"><strong><em>npm</em></strong></a>, <a href="https://www.nuget.org/profiles/HMSCore"><strong><em>nuget</em></strong></a>, and <a href="https://pub.dev/publishers/developer.huawei.com/packages"><strong><em>pub.dev</em></strong></a>.</p><p>In this article, I will introduce the January updates released in 2023 to you. Here are our achievements in this month:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdf8229ea6e7f1552411c3d07721a1c9/href">https://medium.com/media/bdf8229ea6e7f1552411c3d07721a1c9/href</a></iframe><h3>Summary of the month</h3><p>We have updated <strong>Huawei Push </strong>Plugin in four platforms: React Native, Cordova, Xamarin and Flutter. In addition to these; in Flutter we have also updated <strong>Huawei AR Engine</strong> and <strong>Wallet </strong>plugins<strong> </strong>by adding null safety support, in React Native we updated <strong>Safety Detect</strong> plugin by adding TypeScript support.</p><p>Let’s dive into the details of our packages released in this month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*oHIG_YvjmTan2xvQcnC-fA.jpeg" /></figure><h4>Flutter Huawei AR</h4><p>Huawei AR plugin has been updated to 3.7.0+3 version along with breaking changes. Huawei AR plugin on flutter is null safe now! Management of camera permission has been removed, so you are expected to manage the permissions on your own. Multi face detection and tracking support have been added. You can set the light mode to any of the suitable choices from LightMode enum. Memory usage for map data has been optimized. Last but not least, semantic identification for different objects has also been added.</p><p>For the details of the package and changes in the latest version, do not forget to have a look at the <a href="https://pub.dev/packages/huawei_ar/changelog">changelog</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*bSlpe19f4oJU0N-yV32i_w.jpeg" /></figure><h4>Flutter Huawei Wallet</h4><p>Huawei Wallet plugin has been updated to 4.0.5+300 version. This version also includes breaking changes. Flutter Wallet supports the null safety now! All the components that Wallet plugin is depending upon has been updated with this version. There had been some refactoring made on the general structure of plugin. For more details about the changes and details about the Wallet SDK, please have a look at the <a href="https://pub.dev/packages/huawei_wallet/changelog">changelog</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*4QwMUJmg2uvt5LIC2TSn3Q.jpeg" /></figure><h4>React-Native HMS Safety Detect</h4><p>HMS Safety Detect Kit for RN has been updated to 6.7.0.300. This update mostly includes updating the target SDK versions to make sure your apps run properly on Android 13 devices. Moreover, core react libraries have also been updated to the latest versions. Last but not least, typescript support has been added to Safety Detect on React Native platform. For more information about HMS Safety Detect Kit and the latest updates, you are welcome to visit its <a href="https://www.npmjs.com/package/@hmscore/react-native-hms-safetydetect/v/6.7.0-300?activeTab=readme">npm page</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*OUD5l0E6nVWLieuwGdwOPQ.jpeg" /></figure><h4>HMS Push Kit for Flutter, React Native, Cordova &amp; Xamarin</h4><p>Finally, we updated Push Kit on Flutter, React Native, Cordova and Xamarin plugins to version 6.7.0.300. This minor update mostly includes fixes for adapting to android SDK versions from 31 to 33. Also, the core cross-platform libraries are updated to continue providing better performance, stability and compatibility. And more than that, typescript support has been added to Push Kit in React Native.</p><p>As HMS Core Turkey team, we keep updating our cross-platform plugins across the four platforms each month to provide the latest versions of the Huawei Mobile Services to you. So, not to miss the news and the breaking changes of HMS, you can follow our <a href="https://medium.com/huawei-developers">Medium Page</a> and GitHub repositories.</p><ul><li><a href="https://github.com/HMS-Core/hms-react-native-plugin">GitHub - HMS-Core/hms-react-native-plugin: This repo contains all of React-Native HMS plugins.</a></li><li><a href="https://github.com/HMS-Core/hms-cordova-plugin">GitHub - HMS-Core/hms-cordova-plugin: This repo contains all of Cordova HMS plugins.</a></li><li><a href="https://github.com/HMS-Core/hms-flutter-plugin">GitHub - HMS-Core/hms-flutter-plugin: This repo contains all of Flutter HMS plugins.</a></li></ul><p>In addition, if you run into a bug in our packages, do not hesitate to submit an issue to the related repository.</p><p>By the time you see us in the next post, take care of yourselves and keep following our plugins! Bye! 🙋‍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c62ac75a26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/hms-core-what-have-we-done-in-january-2023-b2c62ac75a26">👨‍💻HMS CORE: What have we done in January 2023?</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing The AppIntents Framework — A New Way to Integrate App’s Functionality Into the System]]></title>
            <link>https://medium.com/better-programming/the-appintents-framework-a-new-way-to-hook-up-apps-functionality-to-the-system-96279feb4cce?source=rss-1c3ac955680e------2</link>
            <guid isPermaLink="false">https://medium.com/p/96279feb4cce</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sadık Çoban]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 20:58:20 GMT</pubDate>
            <atom:updated>2022-09-16T07:22:46.216Z</atom:updated>
            <content:encoded><![CDATA[<h4>An expense tracker application to demonstrate the AppIntents framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kd_2Sd0t1QEXckaT" /><figcaption>Photo by <a href="https://unsplash.com/@miguelavtomas?utm_source=medium&amp;utm_medium=referral">Miguel Tomás</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>WWDC has always been one of Apple’s biggest events every year, as the world’s largest technology company announces its latest software and hardware products empowered with cutting-edge technology to its customers, press, the rest of the world, and more importantly to the developers.</p><p>Every iOS developer follows that day to catch up with Apple’s latest products and to add value to their applications by integrating new features released with the new versions of Apple’s operating systems.</p><p>With the release of iOS 16 and Xcode 14, we now have full access to the iOS 16 features in our iPhones and development environments.</p><p>In this article, we will deep dive into one of these cool features Apple introduced with iOS 16 to enhance and make our iOS applications more user-friendly, called the App Intents.</p><p>App Intents framework provides a programmatic method for making your app’s content and features accessible to the system services. These intents are the actions that can be used throughout the system. App Intents make the functionality of your app available in more places including Shortcuts, Spotlight, Focus filters, and Siri which results in a huge benefit for your customers. It sounds fancy right? Then let’s try to understand the structure of these App Intents.</p><p>An intent is a single piece of functionality your app exposes to the system. This functionality can be fetching some data from your app such as finding out the next meeting time, and the place where your order is, and pushing data to your app without launching in the foreground such as adding a new event to your calendar. These features totally depend on the functionality of your app and your creativity.</p><p>An intent is mainly composed of three pieces;</p><ul><li>Metadata (the information about the intent such as the title shown in the shortcuts app).</li><li>Parameters (the inputs your intent requires from the user by using a keyboard, interactions, or Siri).</li><li>Perform method (the responsible for running the main function when the intent is executed).</li></ul><p>App Intents are as easy as writing a few lines of code to integrate into your applications. However, if you want to create more complex features, the framework also enables you to do so. You can use all features Swift provides us to create intents. No need to refactor your projects or some auto-code generation steps.</p><p>In order to better visualize how to add App Intents to an iOS project, I will create an expense tracker application called HarcaMA. The app will not be the best one in the world in terms of its functionality and user interface, but it will be sufficient to explain the power of the App Intents framework.</p><p>In this project, I will use UIKit with a programmatic approach while designing the user interface with SnapKit, but it is also worth noting that you can apply App Intents to your SwiftUI applications as well.</p><p>Our application will have three pages. The first one is the list of expenses we made so far, second one is to add a new expense, and the third one is to edit a current expense. We will also have the opportunity to delete an expense from the application. All these expenses will be stored in Core Data. I will follow the MVVM design pattern with delegation to create this app. So, let’s start with creating our application from Xcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kPQ2ZCI2jyvggVQJ" /></figure><p>Select the storyboard interface, swift as the language and check the Use Core Data option and save the project somewhere in the storage.</p><p>As I said we will not be using storyboard to create user interfaces, we can also remove Main.storyboard file from the project navigator. And start configuring our project.</p><pre>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br><br>        guard let windowScene = (scene as? UIWindowScene) else { return }<br>        window = UIWindow(windowScene: windowScene)<br>        window?.rootViewController = UINavigationController(rootViewController: ViewController())<br>        window?.makeKeyAndVisible()<br>    }</pre><p>Go to the SceneDelegate file, and replace the content of connectionOptions function with the code above.</p><p>Then open up Info.plist file, remove the property with the key UISceneStoryboardFile and value of Main.</p><p>Finally go to Target’s Build Settings, filter the content for Main, and remove the value of UIKit Main Storyboard File Base Name property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*iG3tTTK4RlzELeQz" /></figure><p>Now we safely removed the storyboard and are ready to create user interfaces — after adding SnapKit as a dependency to our project.</p><p>I will use Swift Package Manager, but you can also use CocoaPods or Carthage too. Go to the file menu, and select Add Package from the Xcode option. Search for “<a href="https://github.com/SnapKit/SnapKit.git">https://github.com/SnapKit/SnapKit.git</a>” and press Add Package button.</p><p>After a short period of time, it will ask the package products you want to include into your application. Selecting only SnapKit is enough for our purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PTTT6Gpo3aBwV6cx" /></figure><p>Now you can see SnapKit in PackageDependencies from Project Navigator. Let’s continue with creating the folder structure for our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/0*pPlb7NGYayvs1-aM" /></figure><p>As shown in the image above, I created some folders to organize our project before starting the development. Now, let’s look at our first page which lists our expenses inside a tableview. Since we will work with a UITableView, I think it is a good approach to start with designing the cells of the table view.</p><pre>import UIKit<br>import SnapKit<br>class ExpenseListTableViewCell: UITableViewCell {<br>    static let identifier = &quot;ExpenseListTableViewCell&quot;<br>    <br>    var expense: Expense? {<br>        didSet {<br>            self.configure()<br>        }<br>    }<br>    <br>    private lazy var stackView: UIStackView = {<br>        let stackView = UIStackView()<br>        stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)<br>        stackView.isLayoutMarginsRelativeArrangement = true<br>        stackView.axis = .horizontal<br>        return stackView<br>    }()<br>    <br>    private lazy var tailStackView: UIStackView = {<br>        let stackView = UIStackView()<br>        stackView.spacing = 50<br>        return stackView<br>    }()<br>    <br>    private lazy var titleLabel: UILabel = {<br>        let label = UILabel()<br>        return label<br>    }()<br>    <br>    private lazy var dateLabel: UILabel = {<br>        let label = UILabel()<br>        label.textAlignment = .right<br>        return label<br>    }()<br>    <br>    private lazy var priceLabel: UILabel = {<br>        let label = UILabel()<br>        return label<br>    }()<br>    <br>    private func configure(){<br>        self.titleLabel.text = expense?.title.shorted(to: 15)<br>        self.dateLabel.text = expense?.formattedDate<br>        let price = expense?.price ?? 0<br>        self.priceLabel.text = &quot;$ \(price)&quot;<br>        setupConsts()<br>    }<br>    <br>    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {<br>        super.init(style: style, reuseIdentifier: reuseIdentifier)<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    private func setupConsts(){<br>        tailStackView.addArrangedSubview(dateLabel)<br>        tailStackView.addArrangedSubview(priceLabel)<br>        priceLabel.snp.makeConstraints { $0.width.equalTo(70) }<br>        stackView.addArrangedSubview(titleLabel)<br>        stackView.addArrangedSubview(tailStackView)<br>        contentView.addSubview(stackView)<br>        stackView.snp.makeConstraints { $0.edges.equalToSuperview() }<br>    }<br>}</pre><p>Paste the code above into a file named ExpenseListTableViewCell.swift. Notice that we have a property named expense which represents an Expense, so a model. We run configure function when this expense is set to fill the views with the content of this property. Let’s also add the Expense struct into the Models folder.</p><pre>struct Expense {<br>    let title: String<br>    let date: Date<br>    let price: Double<br>    var formattedDate: String {<br>        let formatter = DateFormatter()<br>        formatter.dateFormat = &quot;MM-dd HH:mm&quot;<br>        return formatter.string(from: date)<br>    }<br>}</pre><p>Our Expense model consists of three stored and one computed properties for now.</p><p>Let’s rename the default ViewController as ExpenseListViewController and start adding our table view.</p><pre>class ExpenseListViewController: UIViewController {<br>    <br>    let viewModel: ExpenseListViewModel<br>    <br>    private lazy var tableView: UITableView = {<br>        let tableView = UITableView()<br>        return tableView<br>    }()<br>    <br>    init(context: NSManagedObjectContext) {<br>        self.viewModel = ExpenseListViewModel(context: context)<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.addSubview(tableView)<br>        tableView.delegate = self<br>        tableView.dataSource = self<br>        tableView.register(ExpenseListTableViewCell.self, forCellReuseIdentifier: ExpenseListTableViewCell.identifier)<br>        configureNavigationBar()<br>    }<br>    <br>    override func viewDidLayoutSubviews() {<br>        super.viewDidLayoutSubviews()<br>        tableView.frame = view.bounds<br>    }<br>    private func configureNavigationBar(){<br>        self.title = &quot;Expenses&quot;<br>        let titleTextAttrs = [NSAttributedString.Key.foregroundColor: UIColor.black]<br>        navigationController?.navigationBar.titleTextAttributes = titleTextAttrs<br>        navigationController?.navigationBar.prefersLargeTitles = true<br>        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(didTapAddExpense))<br>    }<br>    @objc private func didTapAddExpense(){<br>    <br><br>    }<br>}</pre><pre>extension ExpenseListViewController: UITableViewDelegate, UITableViewDataSource {<br>    <br>    func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        1<br>    }<br>    <br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        1<br>    }<br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        UITableViewCell()<br>    }<br>    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -&gt; UIView? {<br>        nil<br>    }<br>    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat {<br>        50<br>    }<br>    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -&gt; CGFloat {<br>        40<br>    }<br>    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        <br>    }<br>}</pre><p>Paste the code above into the view controller. Here we create the table view, set its constraints, register the cell and configure our navigation bar by adding a plus button to add new expenses later on.</p><p>In order to fire up the table view data source and delegate functions, we will also create an extension for our view controller as in above.</p><pre>struct ExpenseListViewModel {<br>    <br>    var expenseList = [Expense]()<br>}</pre><p>Our view model is pretty basic for now, but we will improve it later. Now lets add a view model instance into the view controller. And fill some of the table view delegate functions as in below.</p><pre>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        viewModel.expenseList.count<br>    }</pre><pre>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: ExpenseListTableViewCell.identifier, for: indexPath) as? ExpenseListTableViewCell else { return UITableViewCell() }<br>        cell.expense = viewModel.expenseList[indexPath.row]<br>        return cell<br>    }</pre><pre>    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -&gt; UIView? {<br>        let stackView = UIStackView()<br>        stackView.axis = .horizontal<br>        stackView.backgroundColor = .systemGray<br>        stackView.layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)<br>        stackView.isLayoutMarginsRelativeArrangement = true<br>        let titleLabel = UILabel()<br>        titleLabel.text = &quot;Title&quot;<br>        let tailStackView = UIStackView()<br>        tailStackView.spacing = 100<br>        let dateLabel = UILabel()<br>        dateLabel.text = &quot;Date&quot;<br>        let priceLabel = UILabel()<br>        priceLabel.text = &quot;Price&quot;<br>        stackView.addArrangedSubview(titleLabel)<br>        tailStackView.addArrangedSubview(dateLabel)<br>        tailStackView.addArrangedSubview(priceLabel)<br>        stackView.addArrangedSubview(tailStackView)<br>        return stackView<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*2suN2G4QgcI9qYqG9Mz7ww.png" /></figure><p>Until now, our application will look like this. Now let’s create our create and edit expense page.</p><pre>import UIKit<br><br>protocol AddUpdateExpanseDelegate: AnyObject {<br>    func addNewExpanse(title: String, date: Date, price: Double)<br>    func updateExpanse(with expense: Expense)<br>}<br><br>public enum AddEditExpenseMode {<br>    case update<br>    case add<br>}<br><br>class AddUpdateExpenseViewController: UIViewController {<br>    private let mode: AddEditExpenseMode<br>    private let expense: Expense?<br>    <br>    weak var delegate: AddUpdateExpanseDelegate?<br>    <br>    private lazy var titleTextField: UITextField = {<br>        let textField = UITextField()<br>        textField.attributedPlaceholder = NSAttributedString(string: &quot;Title...&quot;, attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])<br>        textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))<br>        textField.leftViewMode = .always<br>        textField.layer.borderWidth = 1<br>        textField.layer.borderColor = UIColor.lightGray.cgColor<br>        textField.layer.cornerRadius = 12<br>        textField.returnKeyType = .continue<br>        return textField<br>    }()<br>    <br>    private lazy var priceTextField: UITextField = {<br>        let textField = UITextField()<br>        textField.attributedPlaceholder = NSAttributedString(string: &quot;Amount...&quot;, attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])<br>        textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))<br>        textField.leftViewMode = .always<br>        textField.layer.borderWidth = 1<br>        textField.layer.borderColor = UIColor.lightGray.cgColor<br>        textField.layer.cornerRadius = 12<br>        textField.keyboardType = .decimalPad<br>        textField.returnKeyType = .done<br>        return textField<br>    }()<br>    <br>    private lazy var dateStackView: UIStackView = {<br>        let stackView = UIStackView()<br>        stackView.layer.borderWidth = 1<br>        stackView.layer.borderColor = UIColor.lightGray.cgColor<br>        stackView.layer.cornerRadius = 12<br>        stackView.layoutMargins = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)<br>        stackView.isLayoutMarginsRelativeArrangement = true<br>        return stackView<br>    }()<br>    <br>    private lazy var dateLabel: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;Date&quot;<br>        label.textColor = .lightGray<br>        return label<br>    }()<br>    <br>    <br>    private lazy var datePicker: UIDatePicker = {<br>        let datePicker = UIDatePicker(frame: .zero)<br>        datePicker.datePickerMode = .dateAndTime<br>        datePicker.timeZone = TimeZone.current<br>        return datePicker<br>    }()<br>    <br>    private lazy var addUpdateButton: UIButton = {<br>        let button = UIButton()<br>        button.setTitle(self.mode == .add ? &quot;Add Expense&quot; : &quot;Save Changes&quot;, for: .normal)<br>        button.setTitleColor(.white, for: .normal)<br>        button.backgroundColor = .systemPurple<br>        button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12)<br>        button.layer.borderWidth = 1<br>        button.layer.borderColor = UIColor.lightGray.cgColor<br>        button.layer.cornerRadius = 8<br>        button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)<br>        return button<br>    }()<br>    <br>    init(mode: AddEditExpenseMode, expense: Expense?) {<br>        self.mode = mode<br>        self.expense = expense<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        self.hideKeyboardWhenTappedAround()<br>        configureNavigationBar()<br>        view.backgroundColor = .systemBackground<br>        titleTextField.delegate = self<br>        priceTextField.delegate = self<br>        titleTextField.becomeFirstResponder()<br>        addSubviews()<br>    }<br>    <br>    <br>    private func configureNavigationBar(){<br>        self.title = self.mode == .add ? &quot;Add Expense&quot; : &quot;Update Expense&quot;<br>        let titleTextAttrs = [NSAttributedString.Key.foregroundColor: UIColor.label]<br>        navigationController?.navigationBar.titleTextAttributes = titleTextAttrs<br>        navigationController?.navigationBar.prefersLargeTitles = true<br>    }<br>    <br>    private func addSubviews(){<br>        view.addSubview(titleTextField)<br>        view.addSubview(priceTextField)<br>        dateStackView.addArrangedSubview(dateLabel)<br>        dateStackView.addArrangedSubview(datePicker)<br>        view.addSubview(dateStackView)<br>        view.addSubview(addUpdateButton)<br>        guard let expense = self.expense, self.mode == .update else { return }<br>        fillFields(with: expense)<br>    }<br>    <br>    private func fillFields(with expense: Expense){<br>        self.titleTextField.text = expense.title<br>        self.priceTextField.text = String(expense.price)<br>        self.datePicker.date = expense.date<br>    }<br>    <br>    override func viewDidLayoutSubviews() {<br>        titleTextField.snp.makeConstraints { make in<br>            make.top.equalToSuperview().offset(200)<br>            make.leading.equalToSuperview().offset(50)<br>            make.trailing.equalToSuperview().inset(50)<br>            make.height.equalTo(52)<br>        }<br>        priceTextField.snp.makeConstraints { make in<br>            make.leading.trailing.equalTo(titleTextField)<br>            make.top.equalTo(titleTextField.snp.bottom).offset(20)<br>            make.height.equalTo(52)<br>        }<br>        <br>        dateStackView.snp.makeConstraints { make in<br>            make.leading.trailing.equalTo(titleTextField)<br>            make.top.equalTo(priceTextField.snp.bottom).offset(20)<br>            make.height.equalTo(52)<br>        }<br>        <br>        addUpdateButton.snp.makeConstraints { make in<br>            make.trailing.equalTo(titleTextField)<br>            make.top.equalTo(dateStackView.snp.bottom).offset(20)<br>        }<br>    }<br>    <br>    @objc private func didTapButton(){<br>        guard let priceText = priceTextField.text,<br>              let price = Double(priceText),<br>              let title = titleTextField.text else { return }<br>        let date = datePicker.date<br>        if self.mode == .add {<br>            delegate?.addNewExpanse(title: title, date: date, price: price)<br>        } else {<br>            let newExpense = Expense(title: title, date: date, price: price)<br>            delegate?.updateExpanse(with: newExpense)<br>        }<br>        self.dismiss(animated: true)<br>    }<br>    <br>}<br>extension AddUpdateExpenseViewController: UITextFieldDelegate {<br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {<br>        if textField == titleTextField {<br>            priceTextField.becomeFirstResponder()<br>        } else if textField == priceTextField {<br>            view.endEditing(true)<br>            <br>        }<br>        return true<br>    }<br>}</pre><p>As shown above, we will handle both add and update actions in the same view controller, via the mode parameter. We will be using AddUpdateExpanseDelegate protocol to trigger add and edit actions.</p><p>Since our user interfaces are nearly completed, let’s create our Core Data entity model and its configuration files. Open HarcaMA.xcdatamodeld file and tap to Add Entity button below. Name your entity as ExpenseItem and add attributes with the compatible data types as in the image below. Also, select the Manual code generation option from the data model inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*2hykb2iYxGosqOVy" /></figure><p>While you select datamodel file in Xcode, go to the Editor and select Create NSManagedObject Subclass option. When you select your entity model and select create, Xcode will create the CoreDataClass for the Entity, and an extension file including its properties.</p><p>After these steps, If you build your project successfully, we can continue with creating our service struct.</p><pre>struct ExpenseService {<br>    <br>    let context: NSManagedObjectContext<br>    <br>    init(context: NSManagedObjectContext) {<br>        self.context = context<br>    }<br>    <br>    public func fetchExpenseItems(completion: @escaping (Result&lt;[ExpenseItem], ExpenseServiceErrors&gt;) -&gt; (Void)){<br>        do {<br>            let items = try context.fetch(ExpenseItem.fetchRequest())<br>            completion(.success(items))<br>        } catch  {<br>            completion(.failure(.fetchError))<br>        }<br>    }<br>    <br>    public func addExpenseItem(title: String, date: Date, price: Double, completion: @escaping (Bool) -&gt; (Void)){<br>        let newItem = ExpenseItem(context: context)<br>        newItem.title = title<br>        newItem.date = date<br>        newItem.price = price<br>        do {<br>            try context.save()<br>            completion(true)<br>        } catch  {<br>            completion(false)<br>        }<br>    }<br>    <br>    public func updateExpenseItem(with newExpense: Expense, completion: @escaping (Bool) -&gt; (Void)){<br>        guard let prevExpense = context.object(with: newExpense.id) as? ExpenseItem else {<br>            completion(false)<br>            return<br>        }<br>        prevExpense.title = newExpense.title<br>        prevExpense.date = newExpense.date<br>        prevExpense.price = newExpense.price<br>        do {<br>            try context.save()<br>            completion(true)<br>        } catch  {<br>            completion(false)<br>        }<br>    }<br>    <br>    public func deleteExpenseItem(with id: NSManagedObjectID, completion: @escaping (Bool) -&gt; (Void)){<br>        guard let expense = context.object(with: id) as? ExpenseItem else {<br>            completion(false)<br>            return<br>        }<br>        context.delete(expense)<br>        do {<br>            try context.save()<br>            completion(true)<br>        } catch  {<br>            completion(false)<br>        }<br>    }<br>    <br>    public func totalExpenseAmount() -&gt; Double? {<br>        do {<br>            let items = try context.fetch(ExpenseItem.fetchRequest())<br>            let total = items.reduce(0) { $0 + $1.price }<br>            return total<br>        } catch  {<br>            return nil<br>        }<br>    }<br>}<br><br>public enum ExpenseServiceErrors: Error {<br>    case fetchError<br>}</pre><p>As shown above, our service has the basic CRUD operations on ExpenseItem entity. To do these operations safely, we also added an id parameter of type NSManagedObjectID into our Expense model, which is automatically generated for each entry.</p><p>Now we need to modify our view model to make use of functions from our service. Replace the content of view model with the code below.</p><pre>class ExpenseListViewModel {<br>    <br>    var expenseList = [Expense]()<br>    let service: ExpenseService<br>    <br>    init(context: NSManagedObjectContext) {<br>        self.service = ExpenseService(context: context)<br>        fetchExpenses(completion: nil)<br>    }<br>    <br>    public func fetchExpenses(completion: (() -&gt; Void)?){<br>        service.fetchExpenseItems {[weak self] result in<br>            switch result {<br>            case .success(let expenses):<br>                self?.expenseList = expenses.map { Expense(id: $0.objectID, title: $0.title, date: $0.date, price: $0.price) }<br>                completion?()<br>            case .failure(_):<br>                print(&quot;error&quot;)<br>            }<br>        }<br>    }<br>    <br>    public func addExpense(title: String, date: Date, price: Double, completion: @escaping () -&gt; Void){<br>        service.addExpenseItem(title: title, date: date, price: price) {[weak self] success in<br>            if success {<br>                self?.fetchExpenses(completion: completion)<br>            }<br>        }<br>    }<br>    <br>    public func deleteExpense(id: NSManagedObjectID, completion: @escaping () -&gt; Void){<br>        service.deleteExpenseItem(with: id) {[weak self] success in<br>            if success {<br>                self?.fetchExpenses(completion: completion)<br>            }<br>        }<br>    }<br>    <br>    public func updateExpense(with newExpense: Expense, completion: @escaping () -&gt; Void){<br>        service.updateExpenseItem(with: newExpense) {[weak self] success in<br>            if success {<br>                self?.fetchExpenses(completion: completion)<br>            }<br>        }<br>    }<br>    <br>}</pre><p>Then we wil add another extension to the ExpenseListViewController and conform to our protocol. Add the code below into the viewcontroller class.</p><pre>extension ExpanseListViewController: AddUpdateExpanseDelegate {<br>    func updateExpanse(with expense: Expense) {<br>        viewModel.updateExpense(with: expense) {[weak self] in<br>            self?.tableView.reloadData()<br>        }<br>    }<br>    <br>    func addNewExpanse(title: String, date: Date, price: Double) {<br>        viewModel.addExpense(title: title, date: date, price: price) {[weak self] in<br>            self?.tableView.reloadData()<br>        }<br>    }<br>}</pre><p>Then change the content of didSelectRowAt function as in below.</p><pre>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        tableView.deselectRow(at: indexPath, animated: true)<br>        showAlertSheet(for: viewModel.expenseList[indexPath.row])<br>        <br>    }<br>    <br>    private func showAlertSheet(for expense: Expense){<br>        let alert = UIAlertController(title: &quot;What to do with this expense?&quot;, message: expense.title, preferredStyle: .actionSheet)<br>        let deleteAction = UIAlertAction(title: &quot;Delete&quot;, style: .destructive) {[weak self] _ in<br>            guard let strongSelf = self else { return }<br>            strongSelf.viewModel.deleteExpense(id: expense.id) {<br>                strongSelf.tableView.reloadData()<br>            }<br>        }<br>        let editAction = UIAlertAction(title: &quot;Edit&quot;, style: .default) { [weak self] _ in<br>            guard let strongSelf = self else { return }<br>            let vc = AddUpdateExpenseViewController(mode: .update, expense: expense)<br>            vc.delegate = strongSelf<br>            strongSelf.present(UINavigationController(rootViewController: vc), animated: true)<br>        }<br>        alert.addAction(UIAlertAction(title: &quot;Dismiss&quot;, style: .cancel))<br>        alert.addAction(editAction)<br>        alert.addAction(deleteAction)<br>        present(alert, animated: true)<br>    }</pre><p>Congratulations 🎉. Now you have a beautiful expense tracker application. Now let’s jump into the main part of this article, which is AppIntents.</p><h3>Integrating App Intents into the Application</h3><p>In our application, we will create two different App Intents.</p><p>One of these will be to add a new expense record.</p><p>The other will be to get total expense we made so far.</p><p>These features will be accessible from Shortcuts App, Spotlight, and Siri. Let’s start with creating the second intent.</p><p>Go to the Intents folder and create a new Swift file called ShowTotalExpense.swift, and import AppIntents framework.</p><p>Any intent can be created by conforming to a protocol called AppIntent.</p><pre>import AppIntents<br><br>struct ShowTotalExpense: AppIntent {<br>    static var title: LocalizedStringResource = &quot;&quot;<br>    func perform() async throws -&gt; some IntentResult {<br>           return .result()<br>    }<br>}</pre><p>Intent can be created with these two parameters which are title, and perform function in its simplest form. If your perform function needs to execute on the main thread you can achieve this by adding the @MainActor annotation.</p><pre>@MainActor<br>func perform() async throws -&gt; some IntentResult {<br>    print(&quot;You know, I am doing something on the main thread...&quot;)<br>    return .result()<br>}</pre><p>The title parameter is the one shown in the shortcut editor. You can set it to a static value, or set it to a localization key you registered into your Localizable files, and use the value for that key.</p><p>In order not to keep this article longer, we will not deal with localization steps but you can find tons of resources explaining how to add localization support to your iOS application.</p><pre>struct ShowTotalExpense: AppIntent {<br>    static var title: LocalizedStringResource = &quot;Show my total expense&quot;<br>    <br>    func perform() async throws -&gt; some IntentResult &amp; ProvidesDialog {<br>        let total = await getTotalExpanse()<br>        let dialog = IntentDialog(total)<br>        return .result(dialog: dialog)<br>    }<br>    <br>    private func getTotalExpanse() async -&gt; LocalizedStringResource {<br>        let service = await ExpenseService(context: (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)<br>        guard let total = service.totalExpenseAmount() else { return LocalizedStringResource(stringLiteral: &quot;0&quot;) }<br>        return LocalizedStringResource(stringLiteral: String(format: &quot;%2.f&quot;, total))<br>    }<br>}</pre><p>The final look of our intent will be as shown above. We run a service function to get total expense amount and return it. Finally, we provide a dialog as the result of running this intent.</p><p>If you run your app with this code, you won’t see a shortcut created for your application or find it in the spotlight, because we should also tell the system which AppIntents will be available to the user and configure these intents.</p><p>In order to keep the modularization of the project, let’s create a new swift file and name it as HarcaMAShortCuts.swift inside our Intents folder. This file will contain a struct conforming to the AppShortcutsProvider protocol and will be the main entry for the shortcuts.</p><pre>struct HarcaMAShortCuts: AppShortcutsProvider {<br>    static var appShortcuts: [AppShortcut] {<br>        AppShortcut(<br>            intent: ShowTotalExpense(),<br>            phrases: [<br>                &quot;What is my total expense in \(.applicationName)?&quot;,<br>                &quot;Show my total expense in \(.applicationName)&quot;,<br>                &quot;How much did I spend in \(.applicationName)?&quot;<br>            ]<br>        )<br>    }<br>}</pre><p>The struct has a static property named appShortcuts, which is an array of type AppShortcut. Keep in mind that currently we are limited up to 10 app shortcuts for an iOS application. After setting the intent and phrases parameters, now our application can make use of our AppIntent in different places.</p><p>You can add any number of phrases you want. These phrases will be used to trigger the intent’s perform method by typing it into Spotlight or telling it to Siri. The first element of the phrases array will be the one shown to the user.</p><p>Now let’s run our application and see if our app intent is working as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*5KufOyf99t9z3rRjxmzgig.png" /></figure><p>If you see your AppIntent and get the successful results, then be proud of yourself! Now you have created an AppIntent.</p><p>Let’s create our second app intent which enables a user to add a new expense item. Create a new file named AddExpense.swift into Intents folder and add the code below into it.</p><pre>struct AddExpense: AppIntent {<br>    <br>    static var title: LocalizedStringResource = &quot;Add a new expense&quot;<br>    <br>    @Parameter(title: &quot;Title&quot;)<br>    var title: String<br>    <br>    @Parameter(title: &quot;Price&quot;)<br>    var price: Double<br>    <br>    @Parameter(title: &quot;Date&quot;)<br>    var date: Date<br>    <br>    <br>    func perform() async throws -&gt; some IntentResult &amp; ProvidesDialog  {<br>        await addExpense()<br>        let dialog = IntentDialog(&quot;Successfully added your \(title) expense!&quot;)<br>        return .result(dialog: dialog)<br>    }<br>    <br>    <br>    private func addExpense() async {<br>        let service = await ExpenseService(context: (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext)<br>        service.addExpenseItem(title: title, date: date, price: price, completion: {_ in})<br>    }<br>    <br>}</pre><p>Apart from the title parameter and perform function, this intent also has three input parameters. We add the @Parameter property wrapper for this kind of inputs when adding into an AppIntent.</p><p>Each Intent parameter should conform to the AppEnum protocol before using into an AppIntent. If you want to have some custom data types, don’t forget to conform to this protocol. Since our app only uses basic data types, we don’t need as they are already conformed to that protocol.</p><p>Here we run another service method in the perform function after getting the inputs from the user, whether with the keyboard or Siri. Then show a dialog to the user. Now we also need to add this intent into the AppShortcutsProvider.</p><pre>struct HarcaMAShortCuts: AppShortcutsProvider {<br>    static var appShortcuts: [AppShortcut] {<br>        AppShortcut(<br>            intent: ShowTotalExpense(),<br>            phrases: [<br>                &quot;What is my total expense in \(.applicationName)?&quot;,<br>                &quot;Show my total expense in \(.applicationName)&quot;,<br>                &quot;How much did I spend in \(.applicationName)?&quot;<br>            ]<br>        )<br>        <br>        AppShortcut(<br>            intent: AddExpense(),<br>            phrases: [<br>                &quot;Add a new expense to \(.applicationName)&quot;,<br>                &quot;Create an expense in \(.applicationName)&quot;<br>            ]<br>        )<br>    }<br>}</pre><p>If you run the application, you will see our new intent. Let’s try if it works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*EZ5IsAc0HiD4IlcVkMbDpA.png" /></figure><p>Well done, It works like a charm!! We now have another way for our users to register a new expense from many places without opening the app. Believe me, these features make your iOS applications more user-friendly and users will accomplish everyday tasks quickly which results in a huge benefit for both you and your customers.</p><p>Until now we found a way to interact with our application without launching in the foreground. But AppIntents framework allows more than that, you can open some specific part of your application by setting the openAppWhenRun parameter to true in your AppIntent struct, create parameter summaries defining how the intent parameters are populated and show a custom user interface such as a SwiftUI view, create custom entities and write queries to gather them up, return a result from an intent by adding ReturnsResult protocol and use the result in another app intent and so on.</p><p>However, before planning the App Shortcuts you will provide for your app, think about the restrictions as well. You cannot have more than 10 app shortcuts for one iOS application. Also if you would like to show your custom views in App Intents, these views can’t include interactivity or animations. I highly recommend you take these into account before planning your App Intents. Finally, we also should think about the ways that our App Shortcuts will be discoverable by the users.</p><p>Still, the AppIntents framework seems like an awesome way to increase interaction between users and apps and to create more value for our iOS applications. Let’s think about our shortcuts and see the great AppIntent ideas created for iOS apps.</p><p>GitHub repository:</p><p><a href="https://github.com/sadikcoban/HarcaMA">GitHub - sadikcoban/HarcaMA</a></p><h3><strong><em>References</em></strong></h3><ul><li><a href="https://developer.apple.com/documentation/AppIntents">Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2022/10032/">Dive into App Intents</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2022/10170">Implement App Shortcuts with App Intents</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96279feb4cce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/the-appintents-framework-a-new-way-to-hook-up-apps-functionality-to-the-system-96279feb4cce">Introducing The AppIntents Framework — A New Way to Integrate App’s Functionality Into the System</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>