Created
May 23, 2024 11:17
-
-
Save eunjin3786/7d4f3f066dbca8df4c270b2e66821d0d to your computer and use it in GitHub Desktop.
This file contains 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 | |
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