[英]SwiftUI-How to transition between text when a button is pressed
我正在制作一個練習應用程序,我想在不同的練習之間進行轉換,而不需要制作許多單獨的視圖,因為我還制作了一個計時器,如果我這樣做,它會發布太多次。 我想這樣做,以便當我單擊一個按鈕時,它會將所有文本從練習 1 過渡到練習 2,然后再過渡到練習 3,依此類推。 我想使用同一個按鈕轉換所有這些。
到目前為止,我所做的是創建指向包含不同練習的不同視圖的導航路徑,但是當我這樣做時計時器壞了,因為我多次調用它導致它倒計時太快。 我想看看我是否可以在 1 個視圖中包含所有練習並在它們之間進行轉換。 因此,例如我想從以下位置過渡:
Text(exercisePlan.exercise.title) to Text(exercisePlan.exercise2.title) then to Text(exercisePlan.exercise3.title) all with a click of one button
import SwiftUI
import AVKit
struct ExerciseScreenView: View {
@Binding var streaks: Streaks
@Binding var timerStruct: TimerStruct
var countdownTimer = 300
@State var player = AVPlayer()
var exercisePlan: ExercisePlan
@Binding var navigationPath: NavigationPath
func reset() {
timerStruct.countdownTimer = 300
timerStruct.timerRunning = false
}
var body: some View {
VStack {
Form {
Section(header: Text("1st Exercise (Scroll down for exercise steps)")) {
Text(exercisePlan.exercise.title)
.font(.system(size: 35, weight: .medium))
.padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}
Section(header: Text("Video example")) {
VideoPlayer(player: exercisePlan.exercise.video)
.scaledToFit()
.frame(alignment: .center)
.cornerRadius(10)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}
Section(header: Text("Steps:")){
Text(exercisePlan.exercise.steps)
.font(.system(size: 20, weight: .regular))
.padding()
.frame(alignment: .center)
}
}
TimerView(streaks: $streaks, timerStruct: $timerStruct)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 15, trailing: 0))
Button {
navigationPath.append("ExerciseScreen2View")
} label: {
Text("Next exercise")
.padding()
.background((Color(red: 184/255, green: 243/255, blue: 255/255)))
.foregroundColor(.black)
.cornerRadius(10)
.navigationBarBackButtonHidden()
}
.padding(EdgeInsets(top: 0, leading: 10, bottom: 10, trailing: 10))
}
}
}
您要做的是創建一個Exercises
數組。 按下按鈕應該會增加一個索引,以便在您的視圖中顯示相關計划。
小代碼示例:
struct ExerciseScreenView: View {
var exercises: [Exercise]
@State var index: 0
var body: some View {
VStack {
Text(exercises[index].title)
Button {
if exercisePlan.count - 1 > index {
index += 1
} else {
// leave screen
}
} label: {
Text("Next exercise")
}
}
}
}
}
這是一個非常基本的示例,可以進行很多改進,但它為您提供了如何操作的基本概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.