SP GlassKit1.1.0

GlassGallery

Lazy image grid with a zoomable viewer, navigation and cancellable loading.

  • Content
  • iOS 26 · iPadOS 26 · macOS 26
  • Version 1.1.0
  • glass-gallery

Content on an opaque, readable surface. Glass is kept for controls.

GlassGallery running in SP Glass Studio.Capture
Capture of the component running in SP Glass Studio on the iOS 26.5 simulator. Liquid Glass is rendered by the system; this is an image, not a live preview.

Installation

spglass add glass-gallery

Copies the sources and their dependencies into your project. Set up the CLI.

Swift
.package(url: "https://git.spboucher.ai/sp-glasskit.git", from: "1.1.0")

import SPGlassKit
Identifierglass-gallery
ModuleSPGlassMedia
Kindcontent-component — images on an opaque surface; glass only for the viewer's floating buttons
PlatformsiOS 26, iPadOS 26, macOS 26
ExampleExamples/Gallery/Media/GlassGalleryExample.swift

Minimal usage

Swift
GlassGallery(items: [
    GlassGalleryItem(id: "cover", description: "Album cover", image: Image("cover")),
    GlassGalleryItem(id: "photo-1", description: "Harbour at dusk") { try await loadPhoto(1) },
])

Variants

Item initialiserUse
init(id:description:image:)A local Image (asset catalogue, already decoded). Not cached.
init(id:description:load:)@Sendable () async throws -> Image, run when the cell appears.
init(id:description:loadCGImage:)Same with a CGImage, for decoders that work off the main actor.
Gallery optionUse
layout: .gridSquare tiles in as many columns as the width allows (default).
layout: .featuredA large first tile beside two small ones, then rows of three. Falls back to the grid with fewer than three images.
selection:Identifier of an image to outline with a ring and a checkmark (for example the one shown elsewhere on screen). Tapping still opens the viewer.

Parameters

ParameterTypeDefaultMeaning
items[GlassGalleryItem]—Images in display order; identifiers must be unique.
cacheGlassGalleryCache?nilA cache shared with other views. By default the gallery owns one.
cacheCapacityInt64Capacity of the owned cache.
minimumCellWidthCGFloat104Smallest cell width; the adaptive grid fits as many columns as possible.
layoutGlassGalleryLayout.grid.grid or .featured.
selectionString?nilIdentifier of the outlined image; it also carries the selected trait.

GlassBoundedCache<Key, Value> is a public actor with a capacity and least-recently-used eviction (value(for:), insert(_:for:), removeValue(for:), removeAll(), count, keysByRecency). GlassGalleryCache is GlassBoundedCache<String, Image>.

States

  • Loading: a progress indicator on the theme's surface colour.
  • Loaded: the image, cropped to a square in the grid and fitted in the viewer.
  • Failed: a warning symbol with "Media unavailable". Cancelled loads are not failures: the cell loads again when it reappears.
  • Empty (items is empty): a ContentUnavailableView.
  • Viewer: full-screen cover on iOS and iPadOS, sheet on macOS; previous and next buttons (disabled at the ends), close button, caption, pinch and double-tap zoom from 1× to 4×, pan while zoomed.

Advanced example

Swift
let sharedCache = GlassGalleryCache(capacity: 200)

GlassGallery(
    items: listing.photos.map { photo in
        GlassGalleryItem(id: photo.id, description: photo.caption, loadCGImage: {
            let data = try await store.data(for: photo)        // cancellable I/O
            try Task.checkCancellation()
            return try decoder.thumbnail(from: data, maxPixelSize: 600)
        })
    },
    cache: sharedCache,
    minimumCellWidth: 140
)

Accessibility

  • Each cell is a button labelled "Image n of m, description" with the image trait.
  • In the viewer the image carries the same label and supports the VoiceOver zoom action; the buttons are labelled "Previous", "Next" and "Close".
  • Keyboard: left and right arrows navigate, Escape closes.
  • Failure is a symbol plus text. The double-tap zoom animation becomes a short fade with Reduce Motion.

Limits

  • Loading starts in the cell's .task and is cancelled when the cell leaves the screen; the loader must itself honour cancellation for the work to actually stop.
  • The grid and the viewer use the same image: there is no separate thumbnail and full-size source. Provide an image large enough for the viewer, or downscale in the loader and accept a softer zoom.
  • The cache bounds the number of images, not their memory size; choose the capacity for the image size you load.
  • The viewer navigates with buttons and keys, not with a horizontal swipe.
  • Zoom gestures were compiled but not exercised in a running application during verification; the clamping logic is unit-tested.

Example

Complete example (compiled with the package)
import SwiftUI
import CoreGraphics
import SPGlassKit

public struct GlassGalleryExample: GlassExample {
    public static let componentID = "glass-gallery"

    public init() {}

    public var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("Sample data · drawings and gradients generated in code, one slow image and one failing image.")
                .font(.caption)
                .foregroundStyle(.secondary)
                .padding(.horizontal)
            GlassGallery(items: Self.items, cacheCapacity: 12, layout: .featured, selection: "drawing-1")
        }
    }

    private struct SampleLoadingError: Error {}

    static let items: [GlassGalleryItem] = {
        let names = ["Dawn", "Lagoon", "Orchard", "Ember", "Glacier", "Dusk", "Moss", "Coral", "Slate", "Saffron", "Iris", "Tundra"]
        var items = names.enumerated().map { index, name in
            GlassGalleryItem(id: "gradient-\(index)", description: "\(name) gradient", loadCGImage: {
                // Stands in for decoding a file; the sleep makes cancellation observable while scrolling.
                try await Task.sleep(for: .milliseconds(index == 3 ? 1_500 : 120))
                return try gradient(hue: Double(index) / Double(names.count))
            })
        }
        // Local images, already in memory: the drawn compositions of the examples.
        for index in (0..<6).reversed() {
            items.insert(GlassGalleryItem(id: "drawing-\(index)", description: SampleArtwork.title(index), image: SampleArtwork.image(index)), at: 0)
        }
        items.insert(GlassGalleryItem(id: "broken", description: "An image that fails to load", load: { throw SampleLoadingError() }), at: 8)
        return items
    }()

    /// Draws a diagonal two-colour gradient into a bitmap.
    nonisolated static func gradient(hue: Double, side: Int = 256) throws -> CGImage {
        let space = CGColorSpaceCreateDeviceRGB()
        guard let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
            throw SampleLoadingError()
        }
        let colors = [rgb(hue: hue), rgb(hue: (hue + 0.18).truncatingRemainder(dividingBy: 1))] as CFArray
        guard let gradient = CGGradient(colorsSpace: space, colors: colors, locations: [0, 1]) else {
            throw SampleLoadingError()
        }
        context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: side, y: side), options: [])
        guard let image = context.makeImage() else { throw SampleLoadingError() }
        return image
    }

    /// A saturated colour for a hue in 0…1, without any platform colour type.
    nonisolated private static func rgb(hue: Double) -> CGColor {
        let sector = hue * 6
        let x = 1 - abs(sector.truncatingRemainder(dividingBy: 2) - 1)
        let (r, g, b): (Double, Double, Double) = switch Int(sector) % 6 {
        case 0: (1, x, 0)
        case 1: (x, 1, 0)
        case 2: (0, 1, x)
        case 3: (0, x, 1)
        case 4: (x, 0, 1)
        default: (1, 0, x)
        }
        return CGColor(red: 0.25 + 0.6 * r, green: 0.25 + 0.6 * g, blue: 0.25 + 0.6 * b, alpha: 1)
    }
}

#Preview("GlassGallery") { GlassGalleryExample().glassTheme(.crystal) }

Registry entry

Identifierglass-gallery
Version1.1.0
Depends onglass-foundation, glass-icon-button, glass-media-support
FrameworksSwiftUI
Public symbolsGlassGalleryZoom, GlassGalleryItem, GlassGalleryLoading, GlassGalleryLayout, GlassGallery
LicenceMIT
Manifestmanifest.json

Files