mcpField
A
axiom-swiftui-layout-ref

axiom-swiftui-layout-ref

github.com/charleswiltgenデザイン・UI1.2k187 回インストール今日更新
リポジトリ

axiom-swiftui-layout-ref について

SwiftUI で適応型レイアウトを作る開発者向けの API リファレンススキルです。レイアウトコンテナ、ジオメトリ取得、安全領域、サイズ特性の使い方と制約を扱います。

主な機能

  1. 01ViewThatFits による表示選択
  2. 02AnyLayout によるアニメーション切替
  3. 03独自 Layout アルゴリズム
  4. 04ジオメトリ取得 API
  5. 05安全領域とサイズクラス

活用シーン

  1. 01利用可能な空間に応じたビュー選択
  2. 02ビュー ID を保ったレイアウト切替
  3. 03コンテナ寸法に応じたコンテンツ調整

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/charleswiltgen/axiom --skill axiom-swiftui-layout-ref

インストール後、Claude Code で/axiom-swiftui-layout-refを入力して読み込まれたか確認します。

詳細

SwiftUI レイアウト API リファレンス

SwiftUI のアダプティブレイアウトツールに関する包括的な API リファレンスです。判断の指針とアンチパターンについては、axiom-swiftui-layout スキルを参照してください。

概要

このリファレンスでは、アダプティブなインターフェイスを構築するための SwiftUI レイアウト API をすべて説明します。

  • ViewThatFits — バリアントの自動選択(iOS 16+)
  • AnyLayout — 型消去されたアニメーション付きレイアウト切り替え(iOS 16+)
  • Layout Protocol — カスタムレイアウトアルゴリズム(iOS 16+)
  • onGeometryChange — 効率的なジオメトリの読み取り(iOS 16+ にバックポート)
  • GeometryReader — レイアウトフェーズのジオメトリアクセス(iOS 13+)
  • Safe Area Padding — .safeAreaPadding() と .padding() の比較(iOS 17+)
  • Size Classes — 特性に基づく適応
  • iOS 26 Window APIs — フリーフォームウィンドウ、メニューバー、サイズ変更アンカー

ViewThatFits

子ビューを順に評価し、利用可能なスペースに収まる最初のビューを表示します。

基本的な使い方
ViewThatFits {
    // First choice
    HStack {
        icon
        title
        Spacer()
        button
    }

    // Second choice
    HStack {
        icon
        title
        button
    }

    // Fallback
    VStack {
        HStack { icon; title }
        button
    }
}
軸の制約を指定する場合
// Only consider horizontal fit
ViewThatFits(in: .horizontal) {
    wideVersion
    narrowVersion
}

// Only consider vertical fit
ViewThatFits(in: .vertical) {
    tallVersion
    shortVersion
}
仕組み
  1. 各子ビューに fixedSize() を適用します
  2. 利用可能なスペースに対して理想サイズを測定します
  3. 収まる最初の子ビューを返します
  4. どのビューも収まらない場合は、最後の子ビューにフォールバックします
制限事項
  • 選択されたバリアントを取得できません
  • バリアント間をアニメーションできません(代わりに AnyLayout を使用してください)
  • すべてのバリアントを測定します(複雑なビューではパフォーマンスを考慮してください)

AnyLayout

レイアウト間のアニメーション付き遷移を可能にする、型消去されたレイアウトコンテナーです。

基本的な使い方
struct AdaptiveView: View {
    @Environment(\.horizontalSizeClass) var sizeClass

    var layout: AnyLayout {
        sizeClass == .compact
            ? AnyLayout(VStackLayout(spacing: 12))
            : AnyLayout(HStackLayout(spacing: 20))
    }

    var body: some View {
        layout {
            ForEach(items) { item in
                ItemView(item: item)
            }
        }
        .animation(.default, value: sizeClass)
    }
}
使用可能なレイアウトタイプ
AnyLayout(HStackLayout(alignment: .top, spacing: 10))
AnyLayout(VStackLayout(alignment: .leading, spacing: 8))
AnyLayout(ZStackLayout(alignment: .center))
AnyLayout(GridLayout(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 10))
カスタム条件
// Based on Dynamic Type
@Environment(\.dynamicTypeSize) var typeSize

var layout: AnyLayout {
    typeSize.isAccessibilitySize
        ? AnyLayout(VStackLayout())
        : AnyLayout(HStackLayout())
}

// Based on geometry
@State private var isWide = true

var layout: AnyLayout {
    isWide
        ? AnyLayout(HStackLayout())
        : AnyLayout(VStackLayout())
}
条件付きビューではなくこれを使う理由
// ❌ Loses view identity, no animation
if isCompact {
    VStack { content }
} else {
    HStack { content }
}

// ✅ Preserves identity, smooth animation
let layout = isCompact ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
layout { content }

Layout Protocol

配置を完全に制御できるカスタムレイアウトコンテナーを作成します。

基本的なカスタムレイアウト
struct FlowLayout: Layout {
    var spacing: CGFloat = 8

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
        let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
        return calculateSize(for: sizes, in: proposal.width ?? .infinity)
    }

    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
        var point = bounds.origin
        var lineHeight: CGFloat = 0

        for subview in subviews {
            let size = subview.sizeThatFits(.unspecified)

            if point.x + size.width > bounds.maxX {
                point.x = bounds.origin.x
                point.y += lineHeight + spacing
                lineHeight = 0
            }

            subview.place(at: point, proposal: .unspecified)
            point.x += size.width + spacing
            lineHeight = max(lineHeight, size.height)
        }
    }
}

// Usage
FlowLayout(spacing: 12) {
    ForEach(tags) { tag in
        TagView(tag: tag)
    }
}
キャッシュを使用する場合
struct CachedLayout: Layout {
    struct CacheData {
        var sizes: [CGSize] = []
    }

    func makeCache(subviews: Subviews) -> CacheData {
        CacheData(sizes: subviews.map { $0.sizeThatFits(.unspecified) })
    }

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout CacheData) -> CGSize {
        // Use cache.sizes instead of measuring again
    }
}
レイアウト値
// Define custom layout value
struct Rank: LayoutValueKey {
    static let defaultValue: Int = 0
}

extension View {
    func rank(_ value: Int) -> some View {
        layoutValue(key: Rank.self, value: value)
    }
}

// Read in layout
func placeSubviews(...) {
    let sorted = subviews.sorted { $0[Rank.self] < $1[Rank.self] }
}

onGeometryChange

レイアウトへの副作用なしに、効率的にジオメトリを読み取ります。iOS 16+ にバックポートされています。

基本的な使い方
@State private var size: CGSize = .zero

var body: some View {
    content
        .onGeometryChange(for: CGSize.self) { proxy in
            proxy.size
        } action: { newSize in
            size = newSize
        }
}
特定の値を読み取る
// Width only
.onGeometryChange(for: CGFloat.self) { proxy in
    proxy.size.width
} action: { width in
    columnCount = max(1, Int(width / 150))
}

// Frame in coordinate space
.onGeometryChange(for: CGRect.self) { proxy in
    proxy.frame(in: .global)
} action: { frame in
    globalFrame = frame
}

// Aspect ratio
.onGeometryChange(for: Bool.self) { proxy in
    proxy.size.width > proxy.size.height
} action: { isWide in
    self.isWide = isWide
}
座標空間
// Named coordinate space
ScrollView {
    content
        .onGeometryChange(for: CGFloat.self) { proxy in
            proxy.frame(in: .named("scroll")).minY
        } action: { offset in
            scrollOffset = offset
        }
}
.coordinateSpace(name: "scroll")
GeometryReader との比較
項目onGeometryChangeGeometryReader
レイアウトへの影響なし貪欲(スペースを埋める)
評価されるタイミングレイアウト後レイアウト中
用途副作用レイアウト計算
iOS バージョン16+(バックポート済み)13+

GeometryReader

レイアウトフェーズでジオメトリ情報を提供します。貪欲なサイズ設定を行うため、使用は控えめにしてください。

基本的な使い方(制約あり)
// ✅ Always constrain GeometryReader
GeometryReader { proxy in
    let width = proxy.size.width
    HStack(spacing: 0) {
        Rectangle().frame(width: width * 0.3)
        Rectangle().frame(width: width * 0.7)
    }
}
.frame(height: 100)  // Required constraint
GeometryProxy のプロパティ
GeometryReader { proxy in
    // Container size
    let size = proxy.size  // CGSize

    // Safe area insets
    let insets = proxy.safeAreaInsets  // EdgeInsets

    // Frame in coordinate space
    let globalFrame = proxy.frame(in: .global)
    let localFrame = proxy.frame(in: .local)
    let namedFrame = proxy.frame(in: .named("container"))
}
一般的なパターン
// Proportional sizing
GeometryReader { geo in
    VStack {
        header.frame(height: geo.size.height * 0.2)
        content.frame(height: geo.size.height * 0.8)
    }
}

// Centering with offset
GeometryReader { geo in
    content
        .position(x: geo.size.width / 2, y: geo.size.height / 2)
}
よくある間違いを避ける
// ❌ Unconstrained in VStack
VStack {
    GeometryReader { ... }  // Takes ALL space
    Button("Next") { }       // Invisible
}

// ✅ Constrained
VStack {
    GeometryReader { ... }
        .frame(height: 200)
    Button("Next") { }
}

// ❌ Causing layout loops
GeometryReader { geo in
    content
        .frame(width: geo.size.width)  // Can cause infinite loop
}

Safe Area Padding

SwiftUI には、コンテンツの周囲の余白を扱うための主な方法として .padding() と .safeAreaPadding() があります。セーフエリア(ノッチ、Dynamic Island、ホームインジケーター)のあるデバイスで適切なレイアウトを実現するには、それぞれを使う場面を理解することが重要です。

重要な違い
// ❌ WRONG - Ignores safe areas, content hits notch/home indicator
ScrollView {
    content
}
.padding(.horizontal, 20)

// ✅ CORRECT - Respects safe areas, adds padding beyond them
ScrollView {
    content
}
.safeAreaPadding(.horizontal, 20)

重要なポイント:.padding() はビューの端から固定の余白を追加します。.safeAreaPadding() はセーフエリアのインセットの外側に余白を追加します。

それぞれの使いどころ
.padding() を使う場合
  • コンテナー内の兄弟ビュー間に余白を追加する場合
  • どこでも一貫した内部余白を作る場合
  • すでにセーフエリアを考慮するビュー(List、Form など)を扱う場合
  • macOS で装飾用の余白を追加する場合(セーフエリアの懸念がない場合)
VStack(spacing: 0) {
    header
        .padding(.horizontal, 16)  // ✅ Internal spacing

    Divider()

    content
        .padding(.horizontal, 16)  // ✅ Internal spacing
}
.safeAreaPadding() を使う場合(iOS 17+)
  • 画面の端まで広がる全幅コンテンツにマージンを追加する場合
  • 適切なインセットを備えたエッジツーエッジのスクロールを実装する場合
  • セーフエリアへの対応が必要なカスタムコンテナーを作成する場合
  • Liquid Glass またはフルスクリーンマテリアルを扱う場合
// ✅ Edge-to-edge list with custom padding
List(items) { item in
    ItemRow(item)
}
.listStyle(.plain)
.safeAreaPadding(.horizontal, 20)  // Adds 20pt beyond safe areas

// ✅ Full-screen content with proper margins
ZStack {
    Color.blue.ignoresSafeArea()

    VStack {
        content
    }
    .safeAreaPadding(.all, 16)  // Respects notch, home indicator
}
プラットフォームでの利用可否

iOS 17+、iPadOS 17+、macOS 14+、axiom-visionOS 1.0+

それ以前の iOS バージョンでは、手動でセーフエリアを処理してください。

// iOS 13-16 fallback
GeometryReader { geo in
    content
        .padding(.horizontal, 20 + geo.safeAreaInsets.leading)
}

または、条件付きコンパイルを使用してください。

if #available(iOS 17, *) {
    content.safeAreaPadding(.horizontal, 20)
} else {
    content.padding(.horizontal, 20)
        .padding(.leading, safeAreaInsets.leading)
}
エッジごとの使い方
// Top only (below status bar/notch)
.safeAreaPadding(.top, 8)

// Bottom only (above home indicator)
.safeAreaPadding(.bottom, 16)

// Horizontal (left/right of safe areas)
.safeAreaPadding(.horizontal, 20)

// All edges
.safeAreaPadding(.all, 16)

// Individual edges
.safeAreaPadding(EdgeInsets(top: 8, leading: 20, bottom: 16, trailing: 20))
一般的なパターン
エッジツーエッジの ScrollView
ScrollView {
    LazyVStack(spacing: 12) {
        ForEach(items) { item in
            ItemCard(item)
        }
    }
}
.safeAreaPadding(.horizontal, 16)  // Content inset from edges + safe areas
.safeAreaPadding(.vertical, 8)
セーフエリア内のコンテンツを持つフルスクリーン背景
ZStack {
    // Background extends edge-to-edge
    LinearGradient(...)
        .ignoresSafeArea()

    // Content respects safe areas + custom padding
    VStack {
        header
        Spacer()
        content
        Spacer()
        footer
    }
    .safeAreaPadding(.all, 20)
}
入れ子のパディング(併用アプローチ)
// Outer: Safe area padding for device insets
VStack(spacing: 0) {
    content
}
.safeAreaPadding(.horizontal, 16)  // Beyond safe areas

// Inner: Regular padding for internal spacing
VStack {
    Text("Title")
        .padding(.bottom, 8)  // Internal spacing
    Text("Subtitle")
}
判断ツリー
Does your content extend to screen edges?
├─ YES → Use .safeAreaPadding()
│   ├─ Is it scrollable? → .safeAreaPadding(.horizontal/.vertical)
│   └─ Is it full-screen? → .safeAreaPadding(.all)
│
└─ NO (contained within a safe container like List/Form)
    └─ Use .padding() for internal spacing
ビジュアルデバッグ
// Visualize safe area padding (iOS 17+)
content
    .safeAreaPadding(.horizontal, 20)
    .background(.red.opacity(0.2))  // Shows padding area
    .border(.blue)  // Shows content bounds
セーフエリアを手動で処理する方法からの移行
// ❌ OLD: Manual calculation (iOS 13-16)
GeometryReader { geo in
    content
        .padding(.top, geo.safeAreaInsets.top + 16)
        .padding(.bottom, geo.safeAreaInsets.bottom + 16)
        .padding(.horizontal, 20)
}

// ✅ NEW: .safeAreaPadding() (iOS 17+)
content
    .safeAreaPadding(.vertical, 16)
    .safeAreaPadding(.horizontal, 20)
関連 API

.safeAreaInset(edge:) - セーフエリアを縮小する永続的なコンテンツを追加します:

ScrollView {
    content
}
.safeAreaInset(edge: .bottom) {
    // This REDUCES the safe area, content scrolls under it
    toolbarButtons
        .padding()
        .background(.ultraThinMaterial)
}

.ignoresSafeArea() - セーフエリアを完全に無視します:

Color.blue
    .ignoresSafeArea()  // Extends to absolute screen edges
重要な理由

iOS 17 以前:開発者は GeometryReader を使ってセーフエリアのインセットを手動で計算する必要があり、次の問題がありました:

  • コードが冗長になる
  • パフォーマンスのオーバーヘッドが発生する(GeometryReader によって追加のレイアウトパスが強制される)
  • ミスが起きやすい(すべての辺を確認し忘れる)

iOS 17 以降:.safeAreaPadding() を使うと、次のメリットがあります:

  • 宣言型 API(SwiftUI の設計思想に合致)
  • セーフエリアを自動的に認識
  • パフォーマンスが向上(追加のレイアウトパスが不要)
  • 型安全な辺の指定

実際の影響:iPhone 15 Pro で .safeAreaPadding() の代わりに .padding() を使うと、コンテンツが次のようになります:

  • Dynamic Island に重なる(上部)
  • ホームインジケーターに重なる(下部)
  • 画面の角(丸みのある部分)で切れる

サイズクラス

水平方向および垂直方向のサイズ特性を示す環境値です。

サイズクラスの取得
struct AdaptiveView: View {
    @Environment(\.horizontalSizeClass) var horizontalSizeClass
    @Environment(\.verticalSizeClass) var verticalSizeClass

    var body: some View {
        if horizontalSizeClass == .compact {
            compactLayout
        } else {
            regularLayout
        }
    }
}
サイズクラスの値
enum UserInterfaceSizeClass {
    case compact    // Constrained space
    case regular    // Ample space
}
プラットフォームごとの動作

iPhone:

方向水平方向垂直方向
縦向き.compact.regular
横向き(小型).compact.compact
横向き(Plus/Max).regular.compact

iPad:

構成水平方向垂直方向
全画面表示.regular.regular
70% Split View.regular.regular
50% Split View.regular.regular
33% Split View.compact.regular
Slide Over.compact.regular
サイズクラスの上書き
content
    .environment(\.horizontalSizeClass, .compact)

Dynamic Type のサイズ

ユーザーが設定した優先テキストサイズの環境値です。

Dynamic Type の取得
@Environment(\.dynamicTypeSize) var dynamicTypeSize

var body: some View {
    if dynamicTypeSize.isAccessibilitySize {
        accessibleLayout
    } else {
        standardLayout
    }
}
サイズカテゴリ
enum DynamicTypeSize: Comparable {
    case xSmall
    case small
    case medium
    case large           // Default
    case xLarge
    case xxLarge
    case xxxLarge
    case accessibility1  // isAccessibilitySize = true
    case accessibility2
    case accessibility3
    case accessibility4
    case accessibility5
}
Scaled Metric
@ScaledMetric var iconSize: CGFloat = 24
@ScaledMetric(relativeTo: .largeTitle) var headerSize: CGFloat = 44

Image(systemName: "star")
    .frame(width: iconSize, height: iconSize)

iOS 26 のウィンドウ API

ウィンドウのリサイズアンカー
WindowGroup {
    ContentView()
}
.windowResizeAnchor(.topLeading)  // Resize originates from top-left
.windowResizeAnchor(.center)      // Resize from center
メニューバーコマンド(iPad)
@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            CommandMenu("View") {
                Button("Show Sidebar") {
                    showSidebar.toggle()
                }
                .keyboardShortcut("s", modifiers: [.command, .option])

                Divider()

                Button("Zoom In") { zoom += 0.1 }
                    .keyboardShortcut("+")
                Button("Zoom Out") { zoom -= 0.1 }
                    .keyboardShortcut("-")
            }
        }
    }
}
NavigationSplitView の列の制御
// iOS 26: Automatic column visibility
NavigationSplitView {
    Sidebar()
} content: {
    ContentList()
} detail: {
    DetailView()
}
// Columns auto-hide/show based on available width

// Manual control (when needed)
@State private var columnVisibility: NavigationSplitViewVisibility = .all

NavigationSplitView(columnVisibility: $columnVisibility) {
    Sidebar()
} detail: {
    DetailView()
}
シーンフェーズ
@Environment(\.scenePhase) var scenePhase

var body: some View {
    content
        .onChange(of: scenePhase) { oldPhase, newPhase in
            switch newPhase {
            case .active:
                // Window is visible and interactive
            case .inactive:
                // Window is visible but not interactive
            case .background:
                // Window is not visible
            }
        }
}

座標空間

組み込みの座標空間
// Global (screen coordinates)
proxy.frame(in: .global)

// Local (view's own bounds)
proxy.frame(in: .local)

// Named (custom)
proxy.frame(in: .named("mySpace"))
名前付きスペースの作成
ScrollView {
    content
        .onGeometryChange(for: CGFloat.self) { proxy in
            proxy.frame(in: .named("scroll")).minY
        } action: { offset in
            scrollOffset = offset
        }
}
.coordinateSpace(name: "scroll")

// iOS 17+ typed coordinate space
extension CoordinateSpaceProtocol where Self == NamedCoordinateSpace {
    static var scroll: Self { .named("scroll") }
}

ScrollView のジオメトリ(iOS 18 以降)

onScrollGeometryChange
ScrollView {
    content
}
.onScrollGeometryChange(for: CGFloat.self) { geometry in
    geometry.contentOffset.y
} action: { offset in
    scrollOffset = offset
}
ScrollGeometry のプロパティ
.onScrollGeometryChange(for: ScrollGeometry.self) { $0 } action: { geo in
    let offset = geo.contentOffset      // Current scroll position
    let size = geo.contentSize          // Total content size
    let visible = geo.visibleRect       // Currently visible rect
    let insets = geo.contentInsets      // Content insets
}

Lazy コンテナの注意点

再利用の動作

LazyVStack と LazyHStack は必要に応じてビューを作成し、画面外に出ると再利用します。つまり、次の点に注意が必要です:

  • ビューの ID が重要です:高速スクロール中にセルがちらついたり消えたりする場合、ビューの ID が不安定です。アイテムに明示的な .id() を指定してください。
  • onAppear/onDisappear は繰り返し呼び出されます:スクロールに応じてビューが作成・破棄されます。これらを一度だけ行うセットアップに使わないでください。
  • 再利用時に状態がリセットされます:Lazy アイテム内の @State は、再利用されるとリセットされます。状態はモデル層に移してください。
// ❌ Items flash during fast scroll — unstable identity
LazyVStack {
    ForEach(Array(items.enumerated()), id: \.offset) { index, item in
        ItemRow(item: item)  // Identity changes when array mutates
    }
}

// ✅ Stable identity prevents flash/disappear
LazyVStack {
    ForEach(items) { item in  // Uses item.id (Identifiable)
        ItemRow(item: item)
    }
}
Lazy コンテナを使わない方がよい場合
状況代わりに使用理由
50 個未満のアイテムVStack / HStack再利用のオーバーヘッドがなく、よりシンプル
別の Lazy コンテナ内にネストする場合VStack(内側)Lazy コンテナのネストはレイアウトの問題を引き起こす
すべてのアイテムを事前に計測する必要がある場合VStackLazy コンテナは全体のサイズを把握できない

リソース

WWDC:2025-208, 2024-10074, 2022-10056

ドキュメント:/swiftui/layout, /swiftui/viewthatfits

スキル:axiom-swiftui-layout, axiom-swiftui-debugging

コメント