[WWDC26] Code-along: Build powerful drag and drop in SwiftUI
이 글은 WWDC 세션의 transcript 와 영상 화면을 Claude Code 로 정리한 글이고, 실제로 쓴 날은 2026-11-24 다. code 는 세션 page 의 snippet 에 model 과 view 를 직접 채워 Swift package (macOS 27, Swift 6.4, Swift 6 language mode) 로 build 했다.
세션 정보
- 세션: Code-along: Build powerful drag and drop in SwiftUI
- 길이: 15분 21초
- 공개일: 2026-06-08
- 발표: Jack (UI Frameworks team)
- 코드: 세션 page 에 snippet 8개
한 줄 요약
reorderable 과 reorderContainer 로 view 의 순서 바꾸기를 만들고, dragContainer 로 여러 item 을 한 번에 끌게 하고, dragConfiguration 과 dropConfiguration 으로 copy 대신 move 를 쓰고 규칙에 어긋나는 drop 을 막는다.
기존 drag and drop 과 새 기능
SwiftUI 는 iOS 16 부터 draggable 과 dropDestination 으로 drag and drop 을 지원해 왔다. 세션은 이 두 modifier 를 먼저 되짚고, 2027 release 에서 더해진 기능 세 가지를 Solitaire 앱에 차례로 붙여 나간다.
기존 방식
끌려는 view 에 draggable 을 붙이고 옮길 값을 넘긴다. 받는 쪽에는 dropDestination 을 붙이고 받을 type 을 적는다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
예를 들어 card type 을 Transferable 로 만들면 .draggable(card) 한 줄로 card view 를 끌 수 있고, 받는 view 는 .dropDestination(for: Card.self) 로 card 를 받는다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
draggable
[draggable(:)](https://developer.apple.com/documentation/swiftui/view/draggable%28:%29){:target=”_blank”} 는 view 를 drag 의 출발점으로 만든다. 인자로 넘긴 Transferable 값이 drag 에 실려 간다.
dropDestination
dropDestination(for:isEnabled:action:) 는 view 를 drop 을 받는 곳으로 만든다. for 에 적은 type 의 값만 받고, closure 로 받은 값 배열과 DropSession 이 들어온다.
Transferable 이란?
Transferable 은 어떤 type 의 값을 앱 밖으로 내보내거나 받아들일 수 있는 형태로 바꾸는 방법을 적는 protocol 이다. data 에 transfer representation 을 주면 system 이 그 값을 같은 앱 안에서는 물론 다른 앱으로도 실어 나를 수 있다. drag and drop 뿐 아니라 copy and paste, share 도 같은 protocol 을 쓴다. 세션은 자세한 내용을 Meet Transferable 에 맡긴다.
새로 더해진 세 가지
세션이 다루는 내용은 세 가지다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
- Reorderable views: drag 로 view 의 순서를 바꾸는 reordering API
- Drag multiple views: Drag Container API 로 여러 item 을 한 번에 끌기
- Drag configuration: drag 와 drop destination 이 data 를 어떤 방식으로 넘길지 정하기
예제 앱
예제는 Solitaire 다. card 를 pile 사이에서 옮기고, 남은 deck 에서 card 를 뽑아 pile 에 놓는 게임이다. 규칙을 몰라도 따라가는 데 문제가 없다고 세션은 말한다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
Reordering
reordering 은 view 를 끌어서 순서를 바꾸는 동작이다. 세션은 먼저 화면에서 어떤 일이 일어나는지 설명하고, 규칙이 없는 상태로 구현한 다음 게임에 맞게 고친다.
reordering 의 동작
card 네 장이 나란히 놓여 있다고 하자.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
한 장을 끌기 시작하면 그 view 는 hierarchy 에서 들리고, 원래 자리는 빈 placeholder 가 차지한다. 다른 card 위로 가져가면 그 card 들이 자리를 비켜 주고 placeholder 가 drop 될 위치로 옮겨 간다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
손을 놓으면 card 가 새 위치에 들어간다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
프로젝트 구조
Xcode project 는 폴더 두 개로 나뉜다. Game 폴더에는 SwiftData model 과 그 model 을 갱신하는 code 가 있고, Views 폴더에는 SwiftUI view 가 있다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
Preview 에서 먼저 시험하기
앱 전체에 붙이기 전에 GameView 파일의 Preview 에서 card 네 장으로 먼저 시험한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#Preview {
@Previewable @State var cards = [
CardValue(rank: .ace, suit: .clubs),
CardValue(rank: .ace, suit: .diamonds),
CardValue(rank: .ace, suit: .hearts),
CardValue(rank: .ace, suit: .spades)
]
HStack {
ForEach(cards) { card in
CardFaceView(card: card)
}
.reorderable()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.reorderContainer(for: CardValue.self) { difference in
cards.apply(difference: difference)
}
.padding()
.background(.green.gradient)
}
ForEach 에 reorderable 을 붙여 item 을 끌 수 있게 하고, 그 item 들이 움직일 영역인 HStack 에 reorderContainer 를 붙인다. closure 는 reordering 이 끝날 때 불리고, 무엇이 어디로 갔는지를 담은 difference 를 받는다. 이 difference 를 배열에 적용하면 된다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
reorderable
reorderable() 은 ForEach 같은 DynamicViewContent 에 붙이는 modifier 다. 그 안의 item 을 끌어서 순서를 바꿀 수 있는 대상으로 표시한다. SDK 선언으로 보면 iOS 27, macOS 27, watchOS 27, visionOS 27 에서 쓸 수 있고 tvOS 에서는 쓸 수 없다.
reorderContainer
reorderContainer(for:isEnabled:move:) 는 reorderable 한 item 들이 움직이는 영역을 정한다. for 에는 item 의 type 을 적는다. item 은 Identifiable 이어야 하고, move closure 가 받는 difference 는 item 의 id 로 표현된다.
ReorderDifference
ReorderDifference 는 reordering 한 번의 결과다. SDK 선언에는 값이 두 개 있다.
sources: 옮겨진 item 의 id 배열destination: 옮겨 갈 곳. 어느 collection 인지 나타내는collectionID와 그 안의 위치인position을 가진다.position은 어떤 item 앞을 뜻하는.before(id)이거나 맨 끝을 뜻하는.end다.
apply(difference:) 는 SwiftUI 의 API 가 아니다. SDK 에서 찾을 수 없고, 영상의 Preview 화면 아래쪽에 extension Array 로 정의된 모습이 보인다. sample project 가 가진 helper 로 보인다. sample project 를 구하지 못해서 build 확인에는 같은 일을 하는 extension 을 직접 썼다. 아래는 내가 쓴 것이고 세션의 code 가 아니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
extension Array where Element == CardValue {
mutating func apply(difference: ReorderDifference<CardValue, ReorderableSingleCollectionIdentifier>) {
let moved = filter { difference.sources.contains($0) }
removeAll { difference.sources.contains($0) }
switch difference.destination.position {
case .before(let id):
let index = firstIndex(of: id) ?? endIndex
insert(contentsOf: moved, at: index)
case .end:
append(contentsOf: moved)
@unknown default:
append(contentsOf: moved)
}
}
}
옮길 item 을 빼낸 다음 position 이 가리키는 자리에 다시 넣는다. CardValue 는 id 가 자기 자신이 되도록 만들었기 때문에 id 와 값을 같은 것으로 다룬다. collection 을 하나만 쓰는 reorderContainer(for:) 에서는 collection id 의 type 이 ReorderableSingleCollectionIdentifier 로 정해진다.
여러 pile 을 한 container 로 묶기
앱에서는 card 가 pile 사이를 오간다. 그러려면 모든 pile 이 같은 reorderContainer 안에 있어야 한다. pile 일곱 개를 담은 HStack 에 modifier 를 붙인다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
struct GameView: View {
var game: Game
var body: some View {
GeometryReader { proxy in
let spacing: CGFloat = 10
let cardWidth = (proxy.size.width - 6 * spacing) / 7
VStack {
HStack(alignment: .top, spacing: spacing) {
Group {
RemainderView(game: game)
CardBackView()
.hidden()
ForEach(CardValue.Suit.allCases) { suit in
DestinationView(game: game, suit: suit)
}
}
.frame(width: cardWidth)
}
.padding(.bottom, 20)
HStack(alignment: .top, spacing: spacing) {
ForEach(0..<7) { index in
PileView(game: game, index: index)
.frame(width: cardWidth)
}
}
.frame(maxHeight: .infinity, alignment: .top)
// Add the reorder container modifier.
.reorderContainer(for: CardValue.self, in: Card.Group.self) { difference in
game.moveCards(difference: difference)
}
}
}
.padding()
}
}
Preview 때와 다른 점은 in 인자다. container 안에 collection 이 여러 개 있으므로 어느 pile 인지 구분할 type 이 필요하고, 여기서는 Card.Group 을 쓴다. closure 가 받은 difference 는 game.moveCards(difference:) 로 넘겨 model 을 갱신한다.
reorderContainer 의 collection 지정
reorderContainer(for:in:isEnabled:move:) 는 collection 이 여러 개인 container 를 만든다. in 에 적은 type 의 값이 각 collection 의 id 가 되고, difference 의 destination.collectionID 로 돌아온다.
Card.Group, Game, RemainderView, DestinationView 는 sample project 에 있는 type 이다. build 확인에는 Card.Group 을 remainder, destination(Suit), pile(Int) 세 case 를 가진 enum 으로, Game 은 method 가 비어 있는 @Observable class 로 만들었다. 실제 sample project 의 정의는 다를 수 있다.
pile 마다 collection id 주기
각 pile 을 그리는 PileView 의 ForEach 에 reorderable 을 붙인다. 한 container 안에 reorderable 한 ForEach 가 여러 개 있으므로 각각 고유한 id 를 줘야 한다.
여기까지 하고 실행하면 card 를 pile 사이에서 옮길 수 있다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
그런데 문제가 하나 있다. 뒤집혀 있는 face down card 도 들린다. pile 의 card 배열 전체를 reorderable 로 만들었기 때문이다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
face down card 제외하기
ForEach 를 둘로 나눈다. 앞쪽은 face down card 를 그리고 modifier 를 붙이지 않는다. 뒤쪽은 face up card 를 그리고 reorderable 을 붙인다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
struct PileView: View {
var game: Game
var index: Int
@Query var cards: [Card]
var body: some View {
ZStack(alignment: .topLeading) {
CardPlaceholderView()
PileLayout {
let index = firstFaceUpIndex
// Iterates over the face down cards.
ForEach(cards[..<index]) { card in
CardView(card: card)
}
// Iterates over the face up cards.
ForEach(cards[index...], id: \.value) { card in
CardView(card: card)
}
.reorderable(collectionID: Card.Group.pile(index))
}
}
}
var firstFaceUpIndex: Int {
cards.firstIndex { !$0.isFaceDown } ?? cards.endIndex
}
}
firstFaceUpIndex 는 처음으로 앞면이 보이는 card 의 위치다. 그 앞은 face down, 그 뒤는 face up 이다. 뒤쪽 ForEach 는 id: \.value 로 CardValue 를 id 로 쓰는데, container 가 다루는 item type 이 CardValue 이기 때문이다.
reorderable 의 collection id
reorderable(collectionID:) 은 이 ForEach 가 container 안의 어느 collection 인지 알려 준다. 값의 type 은 reorderContainer 의 in 에 적은 type 과 같아야 한다.
snippet 을 그대로 옮기면서 눈에 띈 점이 두 가지 있다. 둘 다 세션이 말한 내용이 아니라 내가 code 를 읽고 본 것이다.
PileLayout안에서let index = firstFaceUpIndex가 property 인index를 가린다. 그래서 글자 그대로 읽으면Card.Group.pile(index)에 들어가는 값은 pile 번호가 아니라 첫 face up card 의 위치다. 세션의 설명은 pile 을 구분하는 id 를 준다는 것이므로 의도는 pile 번호일 것이다. 실제로 쓸 때는 local 상수의 이름을 다르게 하거나self.index로 적는 편이 안전해 보인다.@Query var cards에 조건이 없다. 이대로면 모든 card 를 가져오므로, sample project 에서는 initializer 에서 pile 별 predicate 를 넣어 줄 것으로 짐작한다. snippet 에는 그 부분이 없다.
CardView, CardPlaceholderView, PileLayout 도 sample project 의 view 다. build 확인에는 사각형을 그리는 view 와 child 를 세로로 조금씩 겹쳐 놓는 Layout 을 직접 만들어 썼다.
세션은 이 reordering API 가 drag and drop 을 지원하는 모든 Apple platform 에 새로 들어왔다고 정리한다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
여러 item 한 번에 끌기
Solitaire 에서는 pile 중간의 card 를 끌면 그 위에 쌓인 card 가 함께 따라와야 한다. 지금은 한 장만 들린다. 세션은 일반적인 앱에서 여러 item 을 끄는 방법을 먼저 보여 주고 Solitaire 에 맞는 방법으로 넘어간다.
selection 을 쓰는 일반적인 방법
보통의 앱에서는 selection 을 더한다. tap 으로 여러 item 을 고른 다음,
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
고른 것 가운데 하나를 끌면 나머지가 함께 들린다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
Solitaire 는 selection 이 없다. 어떤 card 를 잡았는지에 따라 함께 갈 card 가 정해진다.
Drag Container 란?
Drag Container 는 container 안의 item 을 끌기 시작할 때 실제로 무엇을 실어 보낼지를 container 가 정하게 하는 API 다. item 하나하나에 draggable(_:) 로 값을 붙이는 대신, item 에는 id 만 주고 container 가 그 id 를 받아 옮길 값들을 돌려준다. id 하나에 값 여러 개를 돌려주면 여러 item 이 한 번에 끌린다.
reorderContainer 는 자체적으로 drag container 와 drop destination 의 기능을 암묵적으로 제공한다. 그래서 지금까지는 따로 적지 않아도 card 가 끌렸다. 이 기본 동작을 바꾸고 싶으면 같은 type 의 dragContainer 를 직접 붙이면 된다.
dragContainer 로 따라오는 card 정하기
reorderContainer 바로 아래에 dragContainer 를 더한다. GameView 의 나머지는 앞과 같아서 바뀐 부분만 옮긴다.
1
2
3
4
5
6
7
.reorderContainer(for: CardValue.self, in: Card.Group.self) { difference in
game.moveCards(difference: difference)
}
// Add dragContainer to customize reorderContainer.
.dragContainer(for: CardValue.self) { cardID in
game.cardStack(startingAt: cardID)
}
closure 는 끌기 시작한 item 의 id 를 받고, 옮길 transferable data 를 돌려준다. game.cardStack(startingAt:) 은 잡은 card 와 그 위에 쌓인 card 를 모두 돌려주는 sample project 의 method 다.
이제 중간 card 를 끌면 위의 card 가 함께 온다. 기본 모양은 첫 card 가 위에 보이는 pile 로 접힌 형태다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
dragContainer
[dragContainer(for:in::)](https://developer.apple.com/documentation/swiftui/view/dragcontainer%28for:in::%29){:target=”_blank”} 는 view 를 drag container 로 만든다. for 의 type 은 reorderContainer 에 적은 type 과 같아야 reorderContainer 의 기본 동작을 대신한다. SDK 에는 id 하나를 받는 형태와 id 여러 개를 받는 형태가 함께 선언되어 있다.
끌리는 동안의 모양 바꾸기
여러 item 이 끌릴 때 preview 가 어떤 모양으로 모일지는 formation 으로 정한다. 세션은 pile, list, stack 가운데서 고를 수 있다고 말하고, card 가 세로로 겹쳐 보이는 stack 을 고른다.
1
2
3
4
5
.dragContainer(for: CardValue.self) { cardID in
game.cardStack(startingAt: cardID)
}
// Have dragged cards appear as a stack.
.dragPreviewsFormation(.stack)
끌리는 card 들이 pile 에 놓여 있을 때와 같은 모양으로 보인다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
dragPreviewsFormation
[dragPreviewsFormation(:)](https://developer.apple.com/documentation/swiftui/view/dragpreviewsformation%28:%29){:target=”_blank”} 은 이 view 에서 시작한 drag 의 preview 들이 어떤 형태로 모일지 정한다. 인자는 DragDropPreviewsFormation 이고 SDK 에는 .default, .none, .pile, .list, .stack 이 있다.
drop destination 위에서의 모양 맞추기
아직 어색한 점이 남는다. card 를 다른 pile 위로 가져가면 모양이 다시 기본으로 돌아간다. drop destination 위에서는 그 destination 이 정한 formation 을 따르는데, reorderContainer 가 가진 drop destination 은 기본값을 쓰기 때문이다.
GameView 의 root layout 인 VStack 에 dropPreviewsFormation 을 붙여 맞춘다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
VStack {
HStack(alignment: .top, spacing: spacing) {
Group {
RemainderView(game: game)
CardBackView()
.hidden()
ForEach(CardValue.Suit.allCases) { suit in
DestinationView(game: game, suit: suit)
}
}
.frame(width: cardWidth)
}
.padding(.bottom, 20)
HStack(alignment: .top, spacing: spacing) {
ForEach(0..<7) { index in
PileView(game: game, index: index)
.frame(width: cardWidth)
}
}
.frame(maxHeight: .infinity, alignment: .top)
.reorderContainer(for: CardValue.self, in: Card.Group.self) { difference in
game.moveCards(difference: difference)
}
.dragContainer(for: CardValue.self) { cardID in
game.cardStack(startingAt: cardID)
}
.dragPreviewsFormation(.stack)
}
// Have a consistent appearance over drop destinations.
.dropPreviewsFormation(.stack)
dragPreviewsFormation 은 pile 들의 HStack 에, dropPreviewsFormation 은 그 바깥의 VStack 에 붙는다는 점이 다르다.
dropPreviewsFormation
[dropPreviewsFormation(:)](https://developer.apple.com/documentation/swiftui/view/droppreviewsformation%28:%29){:target=”_blank”} 은 drag 가 이 view 위에 있을 때 preview 들이 어떤 형태로 모일지 정한다.
가용성
세션은 이 세 modifier 의 가용성을 다음과 같이 정리한다. dragContainer 는 iOS, iPadOS, visionOS 27 에 새로 들어왔고, 세 modifier 모두 macOS 26 이상에서 쓸 수 있다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
Xcode 27 의 SDK 선언을 확인해 보니 dragPreviewsFormation 과 dropPreviewsFormation 은 macOS 26 이상에서만 쓸 수 있고 iOS, tvOS, watchOS, visionOS 에서는 unavailable 로 표시되어 있다. 즉 formation 을 바꾸는 두 modifier 는 지금 SDK 기준으로 macOS 전용이다. 영상의 예제 앱도 Mac window 에서 돈다. iOS 에서 같은 code 를 쓰려면 이 두 줄은 platform 조건으로 감싸야 할 것이다. 이 부분은 세션이 말한 것이 아니라 SDK 에서 확인한 사실이다.
Drag configuration
마지막은 남은 deck 에서 뽑은 card 를 pile 로 옮기는 일이다. 여기서는 data 를 어떤 방식으로 넘길지가 문제가 된다.
copy 와 move
drag and drop 은 기본으로 copy 를 제안한다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
copy 는 앱 사이에서 data 를 옮기거나 새 item 을 끼워 넣을 때 알맞다. 끌리는 item 에 더하기 표시가 붙고, 놓으면 원본은 그대로 남는다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
card game 에서는 card 가 복제되면 안 된다. deck 에서 pile 로 가는 것은 move 여야 한다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
pile 사이의 이동은 reorderContainer 하나가 출발과 도착을 모두 맡았다. deck 에서 pile 로 가는 이동은 다르다. drag source 와 drop destination 이 따로 있고, 양쪽이 각자 의사를 밝혀야 한다.
drag 쪽에서 move 허용하기
남은 deck 은 왼쪽 위의 RemainderView 가 그린다. deck 옆에 뒤집어 놓은 face up card 에는 이미 drag modifier 가 붙어 있다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
여기에 dragConfiguration 을 더해 move 를 허용한다고 밝힌다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
struct RemainderView: View {
@Query var cards: [Card]
var game: Game
var body: some View {
Button {
incrementCardIndex()
} label: {
ZStack {
CardPlaceholderView()
CardBackView()
.opacity(cards.isEmpty ? 0 : 1)
}
}
.buttonStyle(.plain)
.disabled(cards.isEmpty)
ZStack {
CardPlaceholderView()
if let currentCard {
CardFaceView(card: currentCard.value)
.draggable(containerItemID: currentCard.value)
.opacity(currentCard.value == hiddenCard ? 0 : 1)
}
}
.dragContainer(for: CardValue.self) { cardID in
[cardID]
}
// Add the drag configuration to allow me.
.dragConfiguration(DragConfiguration(allowMove: true))
}
}
face up card 는 draggable(containerItemID:) 로 id 만 가지고, 바깥의 dragContainer 가 그 id 를 받아 card 한 장을 돌려준다. 앞 장의 Drag Container 구조를 reorderContainer 없이 쓴 모습이다. 주석 끝의 allow me 는 allow move 의 오타로 보인다.
snippet 에는 currentCard, hiddenCard, incrementCardIndex() 의 정의가 없다. build 확인에는 뽑은 위치를 가리키는 cardIndex 와 hiddenCard 를 @State 로 두고, currentCard 는 그 위치의 card 를 돌려주는 computed property 로 만들었다.
draggable 의 container item id
draggable(containerItemID:containerNamespace:) 은 view 를 drag container 안의 item 으로 표시하고 id 를 준다. 실제로 옮길 값은 바깥의 dragContainer 가 이 id 로 만든다.
dragConfiguration
[dragConfiguration(:)](https://developer.apple.com/documentation/swiftui/view/dragconfiguration%28:%29){:target=”_blank”} 은 이 view 에서 시작하는 drag 가 어떤 operation 을 허용하는지 정한다. DragConfiguration 을 allowMove: true 로 만들면 move 를 받아도 된다는 뜻이 된다.
drop 쪽에서 새 card 받기
drag 쪽이 move 를 허용해도 실제 방식은 drop destination 이 정한다. 그런데 reorderContainer 는 기본으로 container 안에서 일어난 move 만 받는다. 밖에서 들어오는 새 item 을 받으려면 dropDestination 을 직접 더해야 한다. 그리고 dropConfiguration 으로 어느 pile 에 어떤 operation 으로 받을지 정한다.
GameView 의 최종 모습이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
struct GameView: View {
var game: Game
var body: some View {
GeometryReader { proxy in
let spacing: CGFloat = 10
let cardWidth = (proxy.size.width - 6 * spacing) / 7
VStack {
HStack(alignment: .top, spacing: spacing) {
Group {
RemainderView(game: game)
CardBackView()
.hidden()
ForEach(CardValue.Suit.allCases) { suit in
DestinationView(game: game, suit: suit)
}
}
.frame(width: cardWidth)
}
.padding(.bottom, 20)
HStack(alignment: .top, spacing: spacing) {
ForEach(0..<7) { index in
PileView(game: game, index: index)
.frame(width: cardWidth)
}
}
.frame(maxHeight: .infinity, alignment: .top)
.reorderContainer(for: CardValue.self, in: Card.Group.self) { difference in
game.moveCards(difference: difference)
}
.dragContainer(for: CardValue.self) { cardID in
game.cardStack(startingAt: cardID)
}
.dragPreviewsFormation(.stack)
.dragConfiguration(DragConfiguration(allowMove: true))
// Add a drop destination to accept inserts
.dropDestination(for: CardValue.self) { newCards, session in
if let destination = session.reorderDestination(
for: CardValue.self, in: Card.Group.self) {
game.insertCards(newCards, to: destination)
}
}
// Configure where cards will go when reordering,
// and accept them by move.
.dropConfiguration { session in
// Calculate which pile is being dragged over.
let alignedX = session.location.x - 0.5 * spacing
let pile = Int(alignedX / (cardWidth + spacing))
let destination = ReorderDifference<CardValue, Card.Group>
.Destination(position: .end, collectionID: .pile(pile))
// Check if the move is allowed.
let allowed = session.suggestedOperations.contains(.move)
&& game.validateMove(session: session, destination: destination)
let operation: DropOperation = allowed ? .move : .forbidden
return DropConfiguration(operation: operation, destination: destination)
}
}
.dropPreviewsFormation(.stack)
}
.padding()
}
}
dropDestination 의 closure 는 밖에서 들어온 card 와 DropSession 을 받는다. session.reorderDestination(for:in:) 으로 reorder container 안의 어디에 놓였는지를 얻어 game.insertCards(_:to:) 로 넘긴다. pile 사이의 이동은 여전히 reorderContainer 의 closure 가 처리한다. 두 closure 가 역할을 나눠 갖는다.
reorderContainer의 closure: container 안에서 시작해 container 안에서 끝난 이동dropDestination의 closure: container 밖에서 들어온 item
snippet 을 보면 pile 들의 HStack 에도 dragConfiguration(DragConfiguration(allowMove: true)) 가 들어가 있다. 세션은 이 줄을 따로 설명하지 않는다.
reorderDestination
reorderDestination(for:in:) 은 DropSession 의 method 다. 이 drop 이 reorder container 의 어느 collection, 어느 위치에 해당하는지를 ReorderDifference 의 Destination 으로 돌려준다. 해당하는 곳이 없으면 nil 이다.
dropConfiguration
[dropConfiguration(:)](https://developer.apple.com/documentation/swiftui/view/dropconfiguration%28:%29){:target=”_blank”} 은 drag 가 view 위에 있는 동안 불리는 closure 로 이 drop 을 어떻게 받을지 정한다. 최종 결정권은 여기에 있다. closure 는 DropSession 을 받고 DropConfiguration 을 돌려준다.
DropOperation
DropOperation 은 drop 을 어떤 방식으로 처리할지 나타낸다. 여기서는 .move 와 .forbidden 을 쓴다. .forbidden 을 돌려주면 SwiftUI 가 그 자리에 drop 하지 못하게 막는다.
dropConfiguration 이 하는 세 가지 일
closure 안의 code 는 세 단계로 읽으면 된다.
- 받을 pile 을 계산한다. drag 의 x 좌표를 card 폭과 간격으로 나눠 몇 번째 pile 위에 있는지 구하고, 그 pile 의 맨 끝을 가리키는 destination 값을 만든다.
- move 만 지원한다.
session.suggestedOperations에.move가 들어 있는지 확인한다. 보통의 앱이라면 move 가 안 될 때 copy 로 물러서는 길을 두겠지만 card game 에서는 의미가 없다. - 게임 규칙으로 destination 을 검증한다.
game.validateMove(session:destination:)이false면.forbidden을 돌려준다.
마지막 줄의 DropConfiguration(operation:destination:) 은 SDK 선언상 macOS 27 에서만 쓸 수 있고 iOS 와 visionOS 에서는 unavailable 이다. destination 을 직접 지정하는 이 initializer 는 지금 SDK 기준으로 macOS 전용이라는 뜻이다. operation 만 받는 initializer 는 그런 제한이 없다. 이것도 SDK 에서 확인한 사실이고 세션은 말하지 않는다.
결과
deck 에서 뽑은 6 of diamonds 를 7 of spades 가 맨 위에 있는 pile 로 끌어간다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
규칙에 맞는 이동이라 card 가 pile 로 옮겨 가고 deck 쪽에서는 사라진다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
이번에는 queen of diamonds 를 7 of diamonds 가 있는 pile 로 끌어 본다. 규칙에 어긋나므로 drop 이 받아들여지지 않고 card 는 deck 옆 자리로 돌아간다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
세션은 이 장에서 쓴 modifier 세 개를 한 화면에 정리한다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
세션의 마무리
세션은 다음 세 가지를 권하며 끝난다.
출처: WWDC26 - Code-along: Build powerful drag and drop in SwiftUI
- content 를 reorderable 하게 만든다.
- Drag Container API 로 여러 item 을 한 번에 끌 수 있게 한다.
- drag 와 drop 의 configuration 으로 전송 방식을 다듬는다.
시작은 reorderable 과 reorderContainer 두 개면 되고, 그 위에 drag 와 drop modifier 를 조합해서 원하는 만큼 customize 할 수 있다는 것이 세션의 결론이다.
정리
세션에 나온 modifier 를 역할별로 모으면 다음과 같다.
| modifier | 붙이는 곳 | 역할 |
|---|---|---|
reorderable() | ForEach | item 을 순서 바꾸기 대상으로 표시 |
reorderable(collectionID:) | ForEach | collection 이 여러 개일 때 어느 collection 인지 표시 |
reorderContainer(for:) | item 이 움직일 영역 | reordering 결과를 difference 로 받음 |
reorderContainer(for:in:) | 여러 collection 을 감싼 영역 | collection 사이의 이동까지 받음 |
dragContainer(for:) | container | item id 를 받아 실어 보낼 값을 정함 |
draggable(containerItemID:) | item | drag container 안의 item 으로 표시 |
dragPreviewsFormation(_:) | drag 가 시작되는 view | 끌리는 동안의 preview 모양 |
dropPreviewsFormation(_:) | drop 을 받는 view | destination 위에서의 preview 모양 |
dragConfiguration(_:) | drag 가 시작되는 view | move 허용 여부 |
dropDestination(for:) | drop 을 받는 view | 밖에서 들어온 item 을 받음 |
dropConfiguration(_:) | drop 을 받는 view | operation 과 destination 을 최종 결정 |
실제 프로젝트에 가져갈 점은 다음과 같다.
- 순서 바꾸기만 필요하면
ForEach에reorderable, 그 바깥에reorderContainer두 줄이면 된다. closure 에서 difference 를 model 에 적용하는 code 는 직접 써야 한다. - collection 사이를 오가게 하려면 모든 collection 을 한
reorderContainer로 감싸고ForEach마다 고유한 collection id 를 준다. - 끌 수 없어야 하는 item 은
ForEach를 나눠서reorderable을 붙이지 않는다. - 한 item 을 잡았을 때 다른 item 이 함께 가야 하면
dragContainer에서 값을 여러 개 돌려준다. - container 밖에서 들어오는 item 은
reorderContainer가 받지 않는다.dropDestination을 따로 더한다. - 받으면 안 되는 drop 은
dropConfiguration에서.forbidden으로 막는다. 규칙 검증을 한 곳에 모을 수 있다. - move 는 양쪽이 모두 동의해야 한다. drag 쪽은
dragConfiguration으로 허용하고 drop 쪽은dropConfiguration으로 고른다.
관련 글
- [WWDC26] What’s new in SwiftUI: SwiftUI 의 올해 변경 전체