Skip to content

Instantly share code, notes, and snippets.

@eunjin3786
Created May 23, 2024 11:17
Show Gist options
  • Save eunjin3786/7d4f3f066dbca8df4c270b2e66821d0d to your computer and use it in GitHub Desktop.
Save eunjin3786/7d4f3f066dbca8df4c270b2e66821d0d to your computer and use it in GitHub Desktop.
import SwiftUI
struct TotalPricePreferenceKey: PreferenceKey {
static var defaultValue: Double = 0.0
static func reduce(value: inout Double, nextValue: () -> Double) {
value += nextValue()
}
}
struct ContentView: View {
@State private var totalPrice: Double = 0
var body: some View {
NavigationStack {
VStack {
ItemPricesView()
Text("Total: ") + Text(totalPrice, format: .currency(code: "USD"))
}
.navigationTitle("장바구니 🛒")
}
.onPreferenceChange(TotalPricePreferenceKey.self) {
totalPrice = $0
}
}
}
struct ItemPricesView: View {
var body: some View {
List {
ForEach(1..<10) { index in
HStack {
Text("Item #\(index)")
Spacer()
let num = Double.random(in: 10...100)
Text(num, format: .currency(code: "USD"))
.preference(key: TotalPricePreferenceKey.self, value: num)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment