Communitygithub.com

ComeOnOliver/skillshub

참고 — SwiftUI 적응형 레이아웃 API 완전 가이드: ViewThatFits, AnyLayout, Layout 프로토콜, onGeometryChange, GeometryReader, 크기 클래스, iOS 26 윈도우 API

skillshub란 무엇인가요?

이 스킬은 SwiftUI 적응형 레이아웃 개발을 위한 포괄적인 API 레퍼런스입니다. iOS 16+에서 도입된 ViewThatFits(자동 변형 선택), AnyLayout(타입 지워진 애니메이션 레이아웃 전환), Layout 프로토콜(사용자 정의 레이아웃 알고리즘), onGeometryChange(효율적인 지오메트리 읽기), GeometryReader(레이아웃 단계 지오메트리 접근) 등을 자세히 다룹니다. 또한 iOS 17+의 safeAreaPadding()과 iOS 26의 자유로운 형태 윈도우, 메뉴 바, 크기 조절 앵커와 같은 최신 API도 포함합니다. 이 스킬은 Claude Code, Cursor, Codex 등 다양한 AI 에이전트 플랫폼에서 사용할 수 있으며, 각 API의 기본 사용법, 고급 패턴, 성능 고려 사항, 안티 패턴을 명확한 코드 예제와 함께 제공합니다. 특히 GeometryReader 사용 시 주의사항(제약 조건 필수, 무한 루프 방지)과 AnyLayout을 조건부 뷰 전환보다 선호해야 하는 이유를 설명하여 실무에서 바로 적용할 수 있는 지침을 제공합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-swiftui-layout-ref

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

SwiftUI 레이아웃 API 레퍼런스

SwiftUI 적응형 레이아웃 도구에 대한 포괄적인 API 레퍼런스입니다. 결정 가이드와 안티 패턴은 axiom-swiftui-layout 스킬을 참조하세요.

개요

이 레퍼런스는 적응형 인터페이스를 구축하기 위한 모든 SwiftUI 레이아웃 API를 다룹니다:

  • ViewThatFits — 자동 변형 선택 (iOS 16+)
  • AnyLayout — 타입 지워진 애니메이션 레이아웃 전환 (iOS 16+)
  • Layout 프로토콜 — 사용자 정의 레이아웃 알고리즘 (iOS 16+)
  • onGeometryChange — 효율적인 지오메트리 읽기 (iOS 16+ 하위 호환)
  • GeometryReader — 레이아웃 단계 지오메트리 접근 (iOS 13+)
  • 안전 영역 패딩 — .safeAreaPadding() vs .padding() (iOS 17+)
  • 크기 클래스 — 특성 기반 적응
  • iOS 26 윈도우 API — 자유로운 형태의 윈도우, 메뉴 바, 크기 조절 앵커

ViewThatFits

자식 뷰를 순서대로 평가하고 사용 가능한 공간에 맞는 첫 번째 뷰를 표시합니다.

기본 사용법

ViewThatFits {
    // 첫 번째 선택
    HStack {
        icon
        title
        Spacer()
        button
    }

    // 두 번째 선택
    HStack {
        icon
        title
        button
    }

    // 대체
    VStack {
        HStack { icon; title }
        button
    }
}

축 제약 조건 사용

// 가로 맞춤만 고려
ViewThatFits(in: .horizontal) {
    wideVersion
    narrowVersion
}

// 세로 맞춤만 고려
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))

사용자 정의 조건

// Dynamic Type 기반
@Environment(\.dynamicTypeSize) var typeSize

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

// 지오메트리 기반
@State private var isWide = true

var layout: AnyLayout {
    isWide
        ? AnyLayout(HStackLayout())
        : AnyLayout(VStackLayout())
}

조건부 뷰 대신 사용해야 하는 이유

// ❌ 뷰 ID를 잃고 애니메이션 없음
if isCompact {
    VStack { content }
} else {
    HStack { content }
}

// ✅ ID 유지, 부드러운 애니메이션
let layout = isCompact ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
layout { content }

Layout 프로토콜

위치 지정을 완전히 제어하는 사용자 정의 레이아웃 컨테이너를 만듭니다.

기본 사용자 정의 레이아웃

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)
        }
    }
}

// 사용법
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 {
        // 다시 측정하지 않고 cache.sizes 사용
    }
}

레이아웃 값

// 사용자 정의 레이아웃 값 정의
struct Rank: LayoutValueKey {
    static let defaultValue: Int = 0
}

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

// 레이아웃에서 읽기
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
        }
}

특정 값 읽기

// 너비만
.onGeometryChange(for: CGFloat.self) { proxy in
    proxy.size.width
} action: { width in
    columnCount = max(1, Int(width / 150))
}

// 좌표 공간에서의 프레임
.onGeometryChange(for: CGRect.self) { proxy in
    proxy.frame(in: .global)
} action: { frame in
    globalFrame = frame
}

// 종횡비
.onGeometryChange(for: Bool.self) { proxy in
    proxy.size.width > proxy.size.height
} action: { isWide in
    self.isWide = isWide
}

좌표 공간

// 이름이 있는 좌표 공간
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

레이아웃 단계 중 지오메트리 정보를 제공합니다. 탐욕적 크기 조정 때문에 제한적으로 사용하세요.

기본 사용법 (제약 조건)

// ✅ 항상 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)  // 필수 제약 조건

GeometryProxy 속성

GeometryReader { proxy in
    // 컨테이너 크기
    let size = proxy.size  // CGSize

    // 안전 영역 인셋
    let insets = proxy.safeAreaInsets  // EdgeInsets

    // 좌표 공간에서의 프레임
    let globalFrame = proxy.frame(in: .global)
    let localFrame = proxy.frame(in: .local)
    let namedFrame = proxy.frame(in: .named("container"))
}

일반적인 패턴

// 비율 크기 조정
GeometryReader { geo in
    VStack {
        header.frame(height: geo.size.height * 0.2)
        content.frame(height: geo.size.height * 0.8)
    }
}

// 오프셋으로 중앙 정렬
GeometryReader { geo in
    content
        .position(x: geo.size.width / 2, y: geo.size.height / 2)
}

흔한 실수 피하기

// ❌ VStack에서 제약 조건 없음
VStack {
    GeometryReader { ... }  // 모든 공간 차지
    Button("다음") { }       // 보이지 않음
}

// ✅ 제약 조건 있음
VStack {
    GeometryReader { ... }
        .frame(height: 200)
    Button("다음") { }
}

// ❌ 레이아웃 루프 유발
GeometryReader { geo in
    content
        .frame(width: geo.size.width)  // 무한 루프 가능
}

안전 영역 패딩

SwiftUI는 콘텐츠 주변 공간을 처리하는 두 가지 주요 접근 방식을 제공합니다: .padding()과 .safeAreaPadding(). 언제 각각을 사용해야 하는지 이해하는 것은 노치, 다이내믹 아일랜드, 홈 인디케이터가 있는 기기에서 적절한 레이아웃을 위해 중요합니다.

중요한 차이점

// ❌ 잘못됨 - 안전 영역 무시, 콘텐츠가 노치/홈 인디케이터에 닿음
ScrollView {
    content
}
.padding(.horizontal, 20)

// ✅ 올바름 - 안전 영역 존중, 그 너머에 패딩 추가
ScrollView {
    content
}
.safeAreaPadding(.horizontal, 20)

핵심: .padding()은 뷰 가장자리에서 고정 간격을 추가합니다. .safeAreaPadding()은 안전 영역 인셋 너머에 간격을 추가합니다.

각각 언제 사용해야 하는지

.padding() 사용 시기

  • 컨테이너 내 형제 뷰 사이에 간격 추가
  • 일관되게 유지되어야 하는 내부 간격 생성
  • 이미 안전 영역을 존중하는 뷰(List, Form 등) 작업
  • macOS에서 장식용 간격 추가 (안전 영역 문제 없음)
VStack(spacing: 0) {
    header
        .padding(.horizontal, 16)  // ✅ 내부 간격

    Divider()

    content
        .padding(.horizontal, 16)  // ✅ 내부 간격
}

.safeAreaPadding() 사용 시기 (iOS 17+)

  • 화면 가장자리까지 확장되는 전체 너비 콘텐츠에 여백 추가
  • 적절한 인셋이 있는 가장자리 간 스크롤 구현
  • 안전 영역 인식을 필요로 하는 사용자 정의 컨테이너 생성
  • Liquid Glass 또는 전체 화면 재질 작업
// ✅ 가장자리 간 목록과 사용자 정의 패딩
List(items) { item in
    ItemRow(item)
}
.listStyle(.plain)
.safeAreaPadding(.horizontal, 20)  // 안전 영역 너머 20pt 추가

// ✅ 적절한 여백이 있는 전체 화면 콘텐츠
ZStack {
    Color.blue.ignoresSafeArea()

    VStack {
        content
    }
    .safeAreaPadding(.all, 16)  // 노치, 홈 인디케이터 존중
}

플랫폼 가용성

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

이전 iOS 버전의 경우 수동 안전 영역 처리를 사용하세요:

// iOS 13-16 대체
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)
}

가장자리별 사용법

// 위쪽만 (상태 표시줄/노치 아래)
.safeAreaPadding(.top, 8)

// 아래쪽만 (홈 인디케이터 위)
.safeAreaPadding(.bottom, 16)

// 가로 (안전 영역 왼쪽/오른쪽)
.safeAreaPadding(.horizontal, 20)

// 모든 가장자리
.safeAreaPadding(.all, 16)

// 개별 가장자리
.safeAreaPadding(EdgeInsets(top: 8, leading: 20, bottom: 16, trailing: 20))

일반적인 패턴

가장자리 간 ScrollView

ScrollView {
    LazyVStack(spacing: 12) {
        ForEach(items) { item in
            ItemCard(item)
        }
    }
}
.safeAreaPadding(.horizontal, 16)  // 가장자리 + 안전 영역에서 콘텐츠 인셋
.safeAreaPadding(.vertical, 8)

안전한 콘텐츠가 있는 전체 화면 배경

ZStack {
    // 배경이 가장자리 간 확장
    LinearGradient(...)
        .ignoresSafeArea()

    // 콘텐츠는 안전 영역 + 사용자 정의 패딩 존중
    VStack {
        header
        Spacer()
        content
        Spacer()
        footer
    }
    .safeAreaPadding(.all, 20)
}

중첩 패딩 (결합 접근법)

// 외부: 기기 인셋을 위한 안전 영역 패딩
VStack(spacing: 0) {
    content
}
.safeAreaPadding(.horizontal, 16)  // 안전 영역 너머

// 내부: 내부 간격을 위한 일반 패딩
VStack {
    Text("제목")
        .padding(.bottom, 8)  // 내부 간격
    Text("부제")
}

결정 트리

콘텐츠가 화면 가장자리까지 확장됩니까?
├─ 예 → .safeAreaPadding() 사용
│   ├─ 스크롤 가능합니까? → .safeAreaPadding(.horizontal/.vertical)
│   └─ 전체 화면입니까? → .safeAreaPadding(.all)
│
└─ 아니오 (List/Form 같은 안전한 컨테이너 내에 포함됨)
    └─ 내부 간격을 위해 .padding() 사용

시각적 디버깅

// 안전 영역 패딩 시각화 (iOS 17+)
content
    .safeAreaPadding(.horizontal, 20)
    .background(.red.opacity(0.2))  // 패딩 영역 표시
    .border(.blue)  // 콘텐츠 경계 표시

수동 안전 영역 처리에서 마이그레이션

// ❌ 이전: 수동 계산 (iOS 13-16)
GeometryReader { geo in
    content
        .padding(.top, geo.safeAreaInsets.top + 16)
        .padding(.bottom, geo.safeAreaInsets.bottom + 16)
        .padding(.horizontal, 20)
}

// ✅ 새로: .safeAreaPadding() (iOS 17+)
content
    .safeAreaPadding(.vertical, 16)
    .safeAreaPadding(.horizontal, 20)

관련 API

.safeAreaInset(edge:) - 안전 영역을 줄이는 지속적인 콘텐츠 추가:

ScrollView {
    content
}
.safeAreaInset(edge: .bottom) {
    // 이는 안전 영역을 줄입니다. 콘텐츠는 그 아래로 스크롤됩니다.
    toolbarButtons
        .padding()
        .background(.ultraThinMaterial)
}

.ignoresSafeArea() - 안전 영역을 완전히 해제:

Color.blue
    .ignoresSafeArea()  // 절대 화면 가장자리까지 확장

왜 중요한가

iOS 17 이전: 개발자는 GeometryReader로 안전 영역 인셋을 수동으로 계산해야 했으며, 이로 인해:

  • 장황한 코드
  • 성능 오버헤드 (GeometryReader가 추가 레이아웃 패스 강제)
  • 쉬운 실수 (모든 가장자리 확인 잊음)

iOS 17+: .safeAreaPadding() 제공:

  • 선언적 API (SwiftUI 철학과 일치)
  • 자동 안전 영역 인식
  • 더 나은 성능 (추가 레이아웃 패스 없음)
  • 타입 안전 가장자리 지정

실제 영향

...(번역을 위해 잘렸습니다)

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

관련 스킬