Created
July 22, 2022 00:54
-
-
Save tal/b2060a17a6b58ea7b246d6b93a20394b to your computer and use it in GitHub Desktop.
A basic implementation of a stack of cards tied to a model.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// BaseStackView.swift | |
// Sport Range | |
// | |
// Created by Tal Atlas on 7/20/22. | |
// | |
import SwiftUI | |
class NavStack: ObservableObject { | |
@Published | |
var items: [StackContents] = [] | |
} | |
struct StackContents: Identifiable { | |
var id: UUID | |
var color: Color | |
} | |
struct StackItemView: View { | |
var content: StackContents | |
@EnvironmentObject | |
var navStack: NavStack | |
var body: some View { | |
VStack { | |
Button("Add Child") { | |
navStack.items.append(StackContents(id: UUID(), color: .gray)) | |
} | |
} | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
.background(content.color) | |
.cornerRadius(36) | |
} | |
} | |
struct BaseStackView: View { | |
@StateObject | |
var navStack = NavStack() | |
var items: [StackContents] { | |
navStack.items | |
} | |
@GestureState | |
private var offset = CGSize.zero | |
func Card(_ item: StackContents) -> some View { | |
let isLast = item.id == items.last?.id | |
return StackItemView(content: item) | |
.scaleEffect(isLast ? 1 : 0.9) | |
.offset(x: 0, y: isLast ? offset.height : 0) | |
.gesture( | |
DragGesture() | |
.updating($offset) { (value, state, transaction) in | |
guard isLast else { return } | |
state = value.translation | |
} | |
.onEnded { value in | |
if value.predictedEndTranslation.height > 200 { | |
navStack.items.removeLast() | |
} | |
} | |
, | |
including: isLast ? .all : .none | |
) | |
} | |
var body: some View { | |
VStack { | |
if items.isEmpty { | |
Button("append - \(items.count)") { | |
navStack.items.append(.init(id: UUID(), color: .blue)) | |
} | |
} | |
else { | |
ZStack(alignment: .top) { | |
ForEach(items) { item in | |
Card(item) | |
.transition(.move(edge: .bottom)) | |
} | |
} | |
} | |
} | |
.environmentObject(navStack) | |
.animation(.default.speed(1), value: items.count) | |
} | |
} | |
struct BaseStackView_Previews: PreviewProvider { | |
static var previews: some View { | |
BaseStackView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment