背景:我在使用SwiftUI Transitions. 我有一個FormView包含 4 個不同的Sub-Forms. 當用戶按下 時Next-Button,下一個Sub-Form View會顯示一個Transition (.move -> right to left)。
我也有一個Back Button。當用戶按下此按鈕時,將Sub-Form View顯示上一個,當前具有相同的Transition (.move -> right to left)。但是,我想Transition在這種情況下將其反轉為(.move -> left to right)。
代碼
enum FormStep {
case step1, step2, step3, step4
}
struct CustomForm: View {
@State private var step: FormStep = .step1
var body: some View {
// This Button will change the step State to the previous step
Button(action: { withAnimation { previousStep() } } { Text("Previous") }
// This is the Right to Left Transition applied to subForm
subForm
.transition(.asymmetric(insertion: .move(edge: .trailing), removal: .move(edge: .leading)))
// This Button will change the step State to the next step
Button(action: { withAnimation { nextStep() } } { Text("Next") }
}
@ViewBuilder private var subForm: some View {
switch medicationFormVM.step {
case .step1: StepOneSubForm()
case .step2: StepTwoSubForm()
case .step3: StepThreeSubForm()
case .step4: StepFourSubForm()
}
}
}
問題:如您所見,無論您是來回導航,Transition都將始終是right to left. 我怎樣才能實作改變Transition取決于哪個Button被按下的目標?
uj5u.com熱心網友回復:
這是適合您的方法:
enum FormTransition {
case next, back
var value: AnyTransition {
switch self {
case .next:
return AnyTransition.asymmetric(insertion: .move(edge: .trailing), removal: .move(edge: .leading))
case .back:
return AnyTransition.asymmetric(insertion: .move(edge: .leading), removal: .move(edge: .trailing))
}
}
}
struct CustomForm: View {
@State private var step: FormStep = .step1
@State private var transition: AnyTransition = FormTransition.next.value
var body: some View {
Button(action: { transition = FormTransition.back.value; withAnimation { previousStep() } } { Text("Previous") })
subForm
.transition(transition)
Button(action: { transition = FormTransition.next.value; withAnimation { nextStep() } } { Text("Next") })
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/476579.html
下一篇:SwiftUI-過渡影片錯誤
