<?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 Michael Bedar on Medium]]></title>
        <description><![CDATA[Stories by Michael Bedar on Medium]]></description>
        <link>https://medium.com/@zarvox?source=rss-da3faf27c1b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RQnGs-J16ARW7OuuH74ABg.jpeg</url>
            <title>Stories by Michael Bedar on Medium</title>
            <link>https://medium.com/@zarvox?source=rss-da3faf27c1b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:23:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zarvox/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Reusable Grid Component in SwiftUI]]></title>
            <link>https://zarvox.medium.com/building-a-reusable-grid-component-in-swiftui-1f4b146a9620?source=rss-da3faf27c1b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4b146a9620</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Michael Bedar]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 12:08:54 GMT</pubDate>
            <atom:updated>2023-10-02T12:08:54.329Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the joys of working in SwiftUI is how easy the framework makes it to create reusable view components. Making view components is a great way to both reduce code duplication and help enforce consistency throughout your codebase, whether you are creating a few components or an entire design system.</p><p>I recently worked on a small project with two different screens that each needed to display a set of tappable image thumbnail grids. Each grid had a slightly different layout, but they were similar enough that a shared component seemed like a good way to avoid duplication and general view clutter.</p><blockquote>I am using the fantastic (and free) Marvel API (<a href="https://developer.marvel.com/">https://developer.marvel.com</a>) as a source of testing data. To illustrate, I’m going to build a grid to display a list of all Marvel characters as loaded from the API.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkqgctpXmnovDjc2TSfMzw.png" /><figcaption>Data provided by Marvel. © 2014 Marvel</figcaption></figure><h4>Let’s take a look at the original view code I wrote to display this grid, along with a simplified model object.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f0d99d5951ff761c74bbb9daf834e08/href">https://medium.com/media/9f0d99d5951ff761c74bbb9daf834e08/href</a></iframe><p>Inside a GeometryReader, the LazyVGrid is initialized to have exactly three grid cells across, and uses a ForEach loop to iterate over the array of characters in the data model, creating a new custom view for each character, wrapped in a NavigationLink. There is also a view placed right below the ForEach loop that uses its onAppear handler to trigger successive data loads.</p><p>This is not a lot of code, but there are still a few things that I’d rather not duplicate if I am using more than one such grid in my App.</p><ul><li>There is a bit of layout math to calculate the grid size. This app is always going to use a square grid with some fixed number of items across, so it doesn’t make sense to duplicate this calculation code. The reusable component should handle any reasonable column count.</li><li>The basic pattern of ScrollView/LazyVGrid/ForEach is needed for any such grid, and repeating this structure over and over just adds unnecessary levels to the pyramid.</li><li>The inline initialization of Grid and GridItems has two parameters named “spacing”, which is confusing if you want to edit the horizontal or vertical spacing between items in the future.</li></ul><p>In order to make a more reusable component I want to accomplish a few things:</p><ul><li>Take in any array of data items and create one grid item for each</li><li>Have a specifiable number of grid columns</li><li>Have specifiable column and row spacing</li><li>Allow any data item type to be used for the grid</li><li>Allow any view to be used as a grid item view</li><li>Support the simple pagination style shown in the example above</li></ul><h4>Let’s build a reusable view component, which I am calling SquareGrid.</h4><p>SquareGrid will be a view and will require the following parameters to be successful.</p><ul><li>An array of data items. These items can be any type that conforms to Hashable, and will be used as a generic type so that later on when we create our actual grid items we will have data objects of the correct type.</li><li>The number of grid columns. We want our component to be as flexible as possible to support multiple possible designs, so keeping the column count dynamic is vital.</li><li>The variable spacing values to use between columns and rows. Condensing this to one signature with more appropriately named parameters makes it more readable.</li><li>A closure that will be used to allow the actual grid items to be created. It’s important that the SquareGrid not be very opinionated as to what grid item views we use, so we will use a closure to allow these items to be built inline at the usage site.</li></ul><h4>Let’s see some code:</h4><p>Here is the start of the SquareGrid view, with properties that support the requirements above.</p><pre>struct SquareGrid&lt;ViewContent: View, Item: Hashable&gt;: View {<br>    var items: [Item]<br>    var columns: Int = 3<br>    var columnSpacing: CGFloat = 2<br>    var rowSpacing: CGFloat = 2<br><br>    let buildItem: (Item) -&gt; ViewContent<br><br>    var body: some View {<br>      // Body Code Here<br>    }<br>}</pre><p>Along with the numerics for the coloumn count and spacing, we have two generic types in the view definition, one for the data item type, and one for use in our grid item-building closure.</p><p>Now let’s see the body of the view:</p><pre>var body: some View {<br>    GeometryReader { proxy in<br>        let cellSize: CGFloat = proxy.size.width/CGFloat(columns)<br>        ScrollView(.vertical, showsIndicators: false) {<br>            LazyVGrid(columns: .init(repeating:  GridItem(.fixed(cellSize), spacing: columnSpacing), count: columns), spacing: rowSpacing) {<br>                ForEach(items, id: \.self) { item in<br>                    buildItem(item)<br>                        .frame(height: cellSize)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>This code looks the same as the original, non-reusable example above until we get to the contents of the ForEach loop. Here, instead of hard-coding a view to display our grid items, we instead call the buildItem closure, passing in the individual data item from the items array.</p><p>Lastly, we need to support pagination. In the original example, this was accomplished by adding a view.onAppear{ } after the ForEach loop. Since this is a LazyVGrid, this view isn’t rendered until all of the grid items have been displayed, making this technique for simple pagination work. In order to add this functionality to our component, we need to know the total count of items, and we will also need another view-building closure to build the loading item when it is needed.</p><h4>Here is the final code for the SquareGrid with these additions:</h4><pre>struct SquareGrid&lt;ViewContent: View, LoaderContent: View, Item: Hashable&gt;: View {<br>    var items: [Item]<br>    var totalCount: Int<br>    var columns: Int = 3<br>    var columnSpacing: CGFloat = 2<br>    var rowSpacing: CGFloat = 2<br>    var showsIndicators: Bool = false<br><br>    let buildItem: (Item) -&gt; ViewContent<br>    let loadingItem: () -&gt; LoaderContent<br><br>    var body: some View {<br>        GeometryReader { proxy in<br>            let cellSize: CGFloat = proxy.size.width/CGFloat(columns)<br>            ScrollView(.vertical, showsIndicators: showsIndicators) {<br>                LazyVGrid(columns: .init(repeating:  GridItem(.fixed(cellSize), spacing: columnSpacing), count: columns), spacing: rowSpacing) {<br>                    ForEach(items, id: \.self) { item in<br>                        buildItem(item)<br>                            .frame(height: cellSize)<br>                    }<br>                    if items.count &lt; totalCount {<br>                        loadingItem()<br>                            .frame(height: cellSize)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>As you can see, I’ve added the totalCount property, as well as a closure, loadingItem, that will handle the pagination-inducing-view. The component doesn’t know what these items are, but it can tell us when it needs more, and leave us to respond to that as we see fit.</p><blockquote>I also added a boolean property to toggle the ScrollView indicator, since the component encapsulates the ScrollView.</blockquote><p>Now it’s time to update the view code in the original example to make use of this new component.</p><pre>SquareGrid(items: model.characters, totalCount: model.totalCount, columns: 3, columnSpacing: 2, rowSpacing: 2) { item in<br>    NavigationLink(value: item) {<br>        CharacterTileView(character: item)<br>    }<br>} loadingItem: {<br>    ProgressFrameView()<br>        .onAppear {<br>            model.loadMoreCharacters()<br>        }<br>}<br>.navigationDestination(for: Character.self) { item in<br>    CharacterDetailView(character: item)<br>}</pre><p>Here you can see the SquareGrid being initialized, and the two closures working to provide a very SwiftUI friendly way of supplying custom item views to the component.</p><p>By swapping in the component, we have almost halved the lines of code at the usage site, but more importantly we have a reusable view that can build just about any grid, as long as it has square grid items.</p><blockquote>Note: ProgressFrameView is just a ProgressView with some added layout to center it properly.</blockquote><pre>struct ProgressFrameView: View {<br>    var body: some View {<br>        HStack {<br>            Spacer()<br>            ProgressView()<br>            Spacer()<br>        }<br>        .frame(height: 50)<br>    }<br>}</pre><p>I hope this article has been useful to illustrate one way to help create reusable views. Keep an eye out for more in this series. If anyone has ideas for components they’d like to see created please let me know in the comments!</p><p>Full Source: SquareGrid.swift</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2094c21c67e00613e26183db9dea0ef/href">https://medium.com/media/a2094c21c67e00613e26183db9dea0ef/href</a></iframe><p>Usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c3071598464d10c3465364e97f8803a/href">https://medium.com/media/6c3071598464d10c3465364e97f8803a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrUoxmQxzsG2j8EU7FLg0w.png" /><figcaption>Data provided by Marvel. © 2014 Marvel</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4b146a9620" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>