常规使用Timer实现
1. **创建 Timer 实例**
2. **存储 Timer 实例**
3. **启动和停止 Timer**
4. **处理 Timer 触发事件**
@State private var currentIndex = 0
@State private var timer: Timer? = nil // 手动管理 Timer
var body: some View {
VStack {
if !questions.isEmpty {
ZStack {
ForEach(0..<questions.count, id: \.self) { index in
if index == currentIndex {
Text(questions[index])
.systemBoldFont(size: 12~)
.foregroundColor(Color.white)
.padding(.horizontal, 0)
.transition(.asymmetric(
insertion: .move(edge: .bottom), // 进入时从底部滑入
removal: .move(edge: .top) // 退出时向顶部滑出
))
.animation(.easeInOut(duration: 0.5), value: currentIndex) // 动画效果
}
}
}
}
}
.onAppear {
startTimer() // 视图出现时启动 Timer
}
.onDisappear {
stopTimer() // 视图消失时停止 Timer
}
}
// 启动 Timer
private func startTimer() {
timer = Timer.scheduledTimer(
withTimeInterval: 3, // 每 3 秒触发一次
repeats: true
) { _ in
nextQuestion()
}
}
// 停止 Timer
private func stopTimer() {
timer?.invalidate() // 停止 Timer
timer = nil
}
// 切换到下一个问题
private func nextQuestion() {
withAnimation {
currentIndex = (currentIndex + 1) % questions.count
}
}
// 切换到上一个问题
private func previousQuestion() {
withAnimation {
currentIndex = (currentIndex - 1 + questions.count) % questions.count
}
}优点
注意事项
Last updated