【发布时间】:2022-01-15 19:22:27
【问题描述】:
我有一个 TabView,其中我有一个 ForEach 循环用于其中的各种项目,我想使用自动更改选择索引的计时器来更改 TabView 项目的选择。我可以使用具有array.indices 或0..<array.count 的 ForEach 循环来实现它,但是由于使用前面提到的方法是不安全的,所以我想将数组本身简单地传递到 ForEach 循环中,但同时简单地使用数组foreach 循环不会使用计时器或其他编程方式更改所选索引。用户需要手动滚动以更改选择。以下是我尝试过的代码行,谁能指出我做错了什么。
struct ContentView: View {
@State var currentIndex = 0
@State var itemNames = [ItemNames]()
@State var timer: Timer.TimerPublisher = Timer.publish (every: 6, on: .main, in: .common)
var body: some View {
TabView(selection: $currentIndex) {
ForEach(itemNames, id: \.id) { item in
Text(item.name).tag(Int(item.id))
}
}.tabViewStyle(.page(indexDisplayMode: .never))
.onReceive(timer, perform: {
_ in withAnimation {
currentIndex = currentIndex < itemNames.count ? currentIndex + 1 : 0
}
}).onDisappear {
self.cancelTimer()
}.onAppear {
setDemoNames()
self.instantiateTimer()
_ = self.timer.connect()
}
}
func instantiateTimer() {
self.timer = Timer.publish (every: 6, on: .main, in: .common)
return
}
func cancelTimer() {
self.timer.connect().cancel()
return
}
func setDemoNames(){
let item1 = ItemNames(id: "1", name: "John")
let item2 = ItemNames(id: "2", name: "Mark")
let item3 = ItemNames(id: "3", name: "Steve")
let item4 = ItemNames(id: "4", name: "Peter")
itemNames = [item1, item2, item3, item4]
}
}
struct ItemNames : Identifiable, Hashable {
var id:String, name:String;
init(id: String, name: String) {
self.id = id
self.name = name
}
}
【问题讨论】: