I want to assign my storeId, which I am getting from my API. I want to assign it to a global variable. I did this with using onAppear and it works, but it causes lag when the screen opens.
Im looking for better solution for this. Where should I assign the storeId to my global variable?
This is my code:
struct ContentView: View {
var body: some View {
ZStack {
NavigationView {
ScrollView {
LazyVStack {
ForEach(storeArray,id:.id) { item in
if item.type == StoreItemType.store_Index.rawValue {
NavigationImageView(item: item, destinationView: ShowCaseView()
.navigationBarTitle("", displayMode: .inline)
.onAppear{
Config.storeId = item.data?.storeId
})
} else if item.type == StoreItemType.store_link.rawValue {
if item.data?.type == StoreDataType.html_Content.rawValue {
NavigationImageView(item: item, destinationView: WebView())
} else if item.data?.type == StoreDataType.product_List.rawValue {
NavigationImageView(item: item, destinationView: ProductListView())
} else if item.data?.type == StoreDataType.product_Detail.rawValue {
NavigationImageView(item: item, destinationView: ProductDetailView())
}
} else {
fatalError()
}
}
}
}
.navigationBarTitle("United Apps")
}
.onAppear {
if isOpened != true {
getStoreResponse()
}
}
ActivityIndicator(isAnimating: $isAnimating)
}
}
func getStoreResponse() {
DispatchQueue.main.async {
store.storeResponse.sink { (storeResponse) in
isAnimating = false
storeArray.append(contentsOf: storeResponse.items!)
isOpened = true
}.store(in: &cancellable)
store.getStoreResponse()
}
}
}
struct NavigationImageView <DestinationType : View> : View {
var item : Store
var destinationView: DestinationType
var body: some View {
NavigationLink(destination:destinationView ) {
Image(uiImage: (item.banner?.url)!.load())
.resizable()
.aspectRatio(CGFloat((item.banner?.ratio)!), contentMode: .fit)
.cornerRadius(12)
.shadow(radius: 4)
.frame(width: GFloat(UIScreen.main.bounds.width * 0.9),
height: CGFloat((UIScreen.main.bounds.width / CGFloat((item.banner?.ratio) ?? 1))))
}
}
}
question from:
https://stackoverflow.com/questions/65626136/where-should-%c4%b1-assign-variable-in-view-swiftui 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…