I am facing this error
Thread 1: Fatal error: Index out of range
I want to view content by TabView
The number of times come from the number of data from API
The background of his image is displayed on the number of data in API
And make the tab move automatically on this number
this view
import SwiftUI
struct Tap1Section1: View {
private let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
@State private var currentIndex = 0
@State private var nummberIndex = 5
@StateObject var modelname = Api()
var body: some View {
VStack {
TabView(selection: $currentIndex) {
ForEach(modelname.models) { item in
Image("imgCollectionpdf")
.resizable()
.padding(.horizontal,5)
.overlay(
VStack {
Text(item.title)
.foregroundColor(.white)
.padding()
}
)
}
}.tabViewStyle(PageTabViewStyle())
.padding(.bottom,5)
.frame(width: .infinity, height: 140)
.onReceive(timer) { _ in
withAnimation {
currentIndex = currentIndex <
modelname.models.count ? currentIndex 1 : 0
}
}
}
.onAppear {
modelname.getData()
}
}
}
Get the data from the API, is true
And you got it right here modelname.models.count
CodePudding user response:
try this sample code to show your TabView
image and number on top.
Adapt the code for your purpose. You need to have a View while the data is being fetched.
Use .tag
so TabView
knows which one you want to see.
This is just an example, you should re-structure your code, to show
some initial info while the data is fetched, eg. ProgressView
, then show your TabView
.
struct Tap1Section1: View {
private let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
@State private var currentIndex = -1 // <-- here for downloading
@StateObject var modelname = Api()
var body: some View {
VStack {
if currentIndex == -2 {
Text("no data from api") // <-- here for no data
} else if currentIndex == -1 {
ProgressView("downloading...") // <-- here downloading
} else {
TabView(selection: $currentIndex) {
ForEach(Array(modelname.models.enumerated()), id: \.offset) { offset, item in
Image("imgCollectionpdf")
.resizable()
.padding(.horizontal,5)
.overlay(Text(item.title).foregroundColor(.white))
.tag(offset) // <-- here
}
}.tabViewStyle(PageTabViewStyle())
.padding(.bottom,5)
.frame(maxWidth: .infinity, maxHeight: 140) // <-- here
}
}
.onReceive(timer) { _ in
withAnimation {
// -- here
currentIndex = currentIndex 1 < modelname.models.count ? currentIndex 1 : 0
if modelname.models.count == 0 { currentIndex = -2 }
}
}
.onAppear {
modelname.getData()
}
}
}