Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import SwiftUI
- // Model `Recipe` z polem `imagePath`
- struct Recipe: Identifiable, Decodable {
- let id = UUID()
- var filename: String
- var name: String
- var description: String
- var estimatedTime: String
- var imagePath: String // Dodane pole `imagePath`
- }
- struct PhotoGridView: View {
- @State private var recipes: [Recipe] = []
- @State private var selectedRecipe: Recipe? = nil
- private let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 2)
- var body: some View {
- ScrollView {
- LazyVGrid(columns: columns, spacing: 20) {
- ForEach(recipes) { recipe in
- RecipeGridItem(recipe: recipe)
- .onTapGesture {
- selectedRecipe = recipe
- }
- }
- }
- .padding()
- .sheet(item: $selectedRecipe) { recipe in
- RecipeDetailView(recipe: recipe)
- }
- }
- .onAppear {
- loadRecipes()
- }
- }
- private func loadRecipes() {
- if let url = Bundle.main.url(forResource: "recipes", withExtension: "json"),
- let data = try? Data(contentsOf: url),
- let loadedRecipes = try? JSONDecoder().decode([Recipe].self, from: data) {
- // Aktualizacja ścieżki obrazu na pełną ścieżkę
- for index in 0..<loadedRecipes.count {
- let imageName = loadedRecipes[index].filename
- if let imagePath = Bundle.main.path(forResource: "Photos/\(imageName)", ofType: "jpg") {
- loadedRecipes[index].imagePath = imagePath
- }
- }
- self.recipes = loadedRecipes
- }
- }
- }
- struct RecipeGridItem: View {
- let recipe: Recipe
- var body: some View {
- VStack {
- if let uiImage = UIImage(named: recipe.imagePath) {
- Image(uiImage: uiImage)
- .resizable()
- .aspectRatio(contentMode: .fill)
- .frame(width: 150, height: 150)
- .clipped()
- }
- Text(recipe.name)
- .font(.headline)
- .padding(.top, 5)
- Text(recipe.description)
- .font(.subheadline)
- .foregroundColor(.gray)
- Text("Time: \(recipe.estimatedTime)")
- .font(.caption)
- .foregroundColor(.secondary)
- }
- }
- }
- struct RecipeDetailView: View {
- let recipe: Recipe
- var body: some View {
- VStack {
- if let uiImage = UIImage(named: recipe.imagePath) {
- Image(uiImage: uiImage)
- .resizable()
- .aspectRatio(contentMode: .fit)
- .padding()
- }
- Text(recipe.name)
- .font(.title)
- .padding(.bottom, 10)
- Text(recipe.description)
- .font(.body)
- .padding(.bottom, 10)
- Text("Estimated Time: \(recipe.estimatedTime)")
- .font(.subheadline)
- .foregroundColor(.gray)
- }
- .padding()
- }
- }
- struct ContentView: View {
- var body: some View {
- PhotoGridView()
- }
- }
- struct ContentView_Previews: PreviewProvider {
- static var previews: some View {
- ContentView()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement