更新秘诀是确保过渡以动画触发,并在这样做之前告诉它前进的方向。试试这个:
class TabControllerContext : ObservableObject {
@Published var selected = panels.one { didSet {
if previous != selected {
insertion = selected.makeMove(previous)
removal = previous.makeMove(selected)
withAnimation {
trigger = selected
previous = selected
}
}
}}
@Published var trigger = panels.one
@Published var previous = panels.one
var insertion : AnyTransition = .move(edge: .leading)
var removal : AnyTransition = .move(edge: .trailing)
}
struct TabsWithTransitionsView: View {
@EnvironmentObject var context : TabControllerContext
var body: some View {
VStack {
Picker("Select Panel", selection: $context.selected) {
ForEach(panels.allCases) { panel in
panel.label.tag(panel)
}
}.pickerStyle(SegmentedPickerStyle())
ForEach(panels.allCases) { panel in
if context.trigger == panel {
panel.label
.background(panel.color)
.transition(.asymmetric(insertion: context.insertion, removal: context.removal))
}
}
}
}
}
enum panels : Int, CaseIterable, Identifiable {
case one = 1
case two = 2
case three = 3
var label : some View {
switch self {
case .one:
return Label("Tab One", systemImage: "1.circle")
case .two:
return Label("Tab Two", systemImage: "2.square")
case .three:
return Label("Tab Three", systemImage: "asterisk.circle")
}
}
var color : Color {
switch self {
case .one: return Color.red.opacity(0.5)
case .two: return Color.green.opacity(0.5)
case .three: return Color.blue.opacity(0.5)
}
}
func makeMove(_ otherPanel: panels) -> AnyTransition {
return otherPanel.rawValue < self.rawValue ? .move(edge: .trailing) : .move(edge: .leading)
}
// so the enum can be indentified when enumerated
var id : Int { self.rawValue }
}
struct TabsWithTransitionsView_Previews: PreviewProvider {
static var previews: some View {
TabsWithTransitionsView().environmentObject(TabControllerContext())
}
}