Last active
January 9, 2024 23:24
-
-
Save shadone/9c1af9da368ec19025fc69b763b034bc to your computer and use it in GitHub Desktop.
Updating .sheet size at runtime in SwiftUI
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
import SwiftUI | |
extension PresentationDetent { | |
static let small = PresentationDetent.height(200) | |
} | |
struct Item: Identifiable, Hashable { | |
let title: String | |
var id: String { title } | |
} | |
let data: [Item] = [ | |
.init(title: "Hello"), | |
.init(title: "world"), | |
] | |
struct SheetContentDetailView: View { | |
let item: Item | |
let onDismiss: () -> Void | |
var body: some View { | |
VStack { | |
Button(action: { onDismiss() }, label: { | |
Text("Close") | |
}) | |
HStack { | |
Text("Title:") | |
Text(item.title) | |
.font(.title) | |
} | |
} | |
} | |
} | |
struct SheetContentListView: View { | |
@Binding var selectedItem: Item? | |
@State var selection: Item? | |
var body: some View { | |
List(data, id: \.self, selection: $selection) { item in | |
VStack(alignment: .leading) { | |
Text(item.title) | |
.font(.headline) | |
.foregroundStyle(.primary) | |
Text("Subtitle") | |
.font(.subheadline) | |
.foregroundStyle(.secondary) | |
}.tint(.primary) | |
} | |
.onChange(of: selection) { oldValue, newValue in | |
withAnimation { | |
selectedItem = selection | |
} | |
} | |
} | |
} | |
struct SheetView: View { | |
@Binding var isPresented: Bool | |
@Binding var selectedDetent: PresentationDetent | |
@State var detailItem: Item? | |
var body: some View { | |
if let detailItem { | |
SheetContentDetailView( | |
item: detailItem, | |
onDismiss: { | |
self.detailItem = nil | |
selectedDetent = .small | |
} | |
) | |
.transition(.push(from: .bottom)) | |
.onAppear { | |
if selectedDetent == .small { | |
// selectedDetent = .medium | |
} | |
} | |
} else { | |
SheetContentListView(selectedItem: $detailItem) | |
} | |
} | |
} | |
struct ContentView: View { | |
@State private var isShowingSheet = false | |
@State var currentDetent: PresentationDetent = .small | |
var body: some View { | |
VStack { | |
Button("Show Sheet") { | |
isShowingSheet = true | |
} | |
} | |
.sheet( | |
isPresented: $isShowingSheet, | |
onDismiss: { | |
currentDetent = .medium | |
} | |
) { | |
SheetView( | |
isPresented: $isShowingSheet, | |
selectedDetent: $currentDetent | |
) | |
.presentationDetents([.medium, .small], selection: $currentDetent) | |
.presentationBackgroundInteraction(.enabled) | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment