自动滑动切换(SwiftUI)

Automatic slide switching (SwiftUI)

我不明白为什么定时器不工作,文本不自动滚动。

我试过这样做:

ForEach(0..<numberText)

但是我得到这样的错误:

Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'some View' conform to 'TableRowContent'

完整代码:

let numberText = ["text1","text2","text3","text4"]

struct TextNew: View {
    
    private let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
    @State private var index = 0
    
    let textdata = TextData.getAllText()
    
    var body: some View {
        
        GeometryReader { proxy in
            
            TabView(selection: $index) {
                
                ForEach(numberText, id: \.self) { num in
                    
                    Text("\(num)")
                        .font(.system(size: 10))
                        .foregroundColor(.white)
                        .tag(num)
                        .padding(.bottom, 50)
                    
                }
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            .frame(height: 80)
            .onReceive(timer, perform: { _ in
                withAnimation {
                    index = index < numberText.count ? index + 1 : 0
                    
                }
            })
            
        }
    }
}

感谢您的帮助,我是新手

试试这个:

struct TextNew: View {
    
    private let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
    @State private var index = 1
    @State private var selectedNum: String = ""
    
    var body: some View {
        
        GeometryReader { proxy in
            
            TabView(selection: $selectedNum) {
                
                ForEach(numberText, id: \.self) { num in
                    Text("\(num)")
                        .font(.system(size: 10))
                        .foregroundColor(.white)
                        .padding(.bottom, 50)
                }
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            
            .onReceive(timer, perform: { _ in
                withAnimation {
                    index = index < numberText.count ? index + 1 : 1
                    selectedNum = numberText[index - 1]
                }
            })
            
        }
    }
}

解释:

这不起作用的原因是您的 .tagTabView 声明中的 $index 之间的类型不匹配。这些必须匹配。顺便说一句,你不需要这里的 .tag 因为你在你的 ForEach 循环中将它设置为 .self