我正面臨這個錯誤
Thread 1: Fatal error: Index out of range
我想通過 TabView 查看內容
次數來自API的資料數
他的圖片背景顯示在API中的資料數量上
并使標簽在這個數字上自動移動
這種觀點
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()
}
}
}
從 API 獲取資料,是真的modelname.models.count
uj5u.com熱心網友回復:
嘗試使用此示例代碼TabView
在頂部顯示您的影像和編號。根據您的目的調整代碼。在獲取資料時,您需要有一個視圖。使用.tag
所以TabView
知道你想看哪一個。
這只是一個示例,您應該重新構建代碼,以在獲取資料時顯示一些初始資訊,例如。ProgressView
,然后顯示您的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()
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470111.html
上一篇:通過Windows命令列將表格添加到Markdown檔案
下一篇:在API中存盤傳入資料的數量