article

Sunday, February 20, 2022

SwiftUI Show Model Data to Sheet - Sheets and ForEach

SwiftUI Show Model Data to Sheet - Sheets and ForEach

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI
 
struct ContentView : View {
     
    @State var fruit: Fruits?
    
    var body: some View {
        VStack(spacing: 20) {
            ForEach(post) { i in
                Button(i.title) {
                    fruit = .init(id: i.id, title: i.title, price: i.price)
                }
                .foregroundColor(.white)
                .frame(width: 300, height: 50)
                .background(Color.orange)
                .cornerRadius(10)
                .sheet(item: $fruit) { rs in
                    DetailsView(viewdata: rs)
                }
            }
        }
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct DetailsView: View {

    @State var viewdata: Fruits
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        
        VStack {
            Button("Dismiss") {
                presentationMode.wrappedValue.dismiss()
            }
            Spacer()
            Text(viewdata.title)
                .font(.title)
            Text(viewdata.price)
                .font(.title)
            Spacer()
        }
    }
}

struct Fruits: Identifiable {

    let id: Int
    let title: String
    let price : String
}

var post = [
    Fruits(id: 0, title: "Strawberry", price: "45"),
    Fruits(id: 1, title: "Pineapples", price: "89"),
    Fruits(id: 2, title: "Apple", price: "5"),
    Fruits(id: 3, title: "Watermelon", price: "10"),
    Fruits(id: 4, title: "Orange", price: "32"),
    Fruits(id: 5, title: "Banana", price: "56")
]

Related Post