I am trying to call a detailed view of an item when an item is tapped. In this case, the item is a pair of trousers in the MarketplaceTrouserView. When I call TrouserDetailView, I get an error. This must be to do with initialising but I've repeatedly tried this and failed. What could be the solution?
MarketplaceTrouserView:
import SwiftUI
struct MarketplaceTrouserView: View {
@StateObject var MarketplaceModel = MarketplaceViewModel()
@State private var selectedMarketplaceFilter: MarketplaceFilterViewModel = .trouser
@State var showDetailTrouser = false
@State var selectedTrouser : Trouser!
@EnvironmentObject var sharedData: SharedDataModel
var body: some View {
var columns = Array(repeating: GridItem(.flexible()), count: 2)
ZStack{
VStack{
HStack {
Text("Find Trousers To Buy")
}
}
}
if MarketplaceModel.trousers.isEmpty{
ProgressView()
}
else{
ScrollView {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(),spacing: 10), count: 2),spacing: 20){
ForEach(MarketplaceModel.filteredTrouser){trouser in
// Trouser items in grid view
TrouserView(trouserData: trouser)
.onTapGesture {
withAnimation {
selectedTrouser = trouser
showDetailTrouser.toggle()
}
}
}
}
}
}
}
if selectedTrouser != nil && showDetailTrouser{
TrouserDetailView(/*Here is the error asking for trouserData & showDetailTrouser*/)
}
}
}
}
TrouserDetailView:
import SwiftUI
import SDWebImageSwiftUI
struct TrouserDetailView: View {
@State var trouserData : Business
@State var showDetailTrouser: Bool
@EnvironmentObject var sharedData: SharedDataModel
@EnvironmentObject var marketplaceData: MarketplaceViewModel
var body: some View {
ScrollView {
VStack{
HStack {
Button(action: {
withAnimation(.easeOut){showDetailTrouser.toggle()}
}) {
Image(systemName: "arrow.backward.circle.fill")
}
Text(trouserData.trouser_name)
}
VStack {
WebImage(url: URL(string: trouserData.trouser_image))
}
}
}
}
Trouser Model:
import SwiftUI
import FirebaseFirestoreSwift
import Firebase
struct Trouser: Identifiable, Codable {
@DocumentID var id: String?
var trouser_name: String = ""
var trouser_image: String = ""
}
The error is when i call TrouserDetailView (as marked in the code)
CodePudding user response:
By the logic of provided code, state is not needed for the first one and second should be replaced with binding, ie.
struct TrouserDetailView: View {
var trouserData : Trouser
@Binding var showDetailTrouser: Bool
// ...
and call
if selectedTrouser != nil && showDetailTrouser {
TrouserDetailView(trouserData: selectedTrouser,
showDetailTrouser: $showDetailTrouser)
}
CodePudding user response:
@State var trouserData : Business @State var showDetailTrouser: Bool
These variables you must initialize the value locally or switch to @Binding
to bind the data with the parent variables.