0

是否有可能拥有三个(超过 2 个!)根据风格从侧面进出动画的Picker视图SegmentedPickerStyle()

选择器中只有 2 个项目会使作业静态化,因此.transition(.move(edge: .leading))第一个视图和.transition(.move(edge: .trailing))最后一个视图上的 a 就足够了。但是超过2个呢?

也许有一种方法可以使edge: ...转换的参数动态设置为.leadingor.trailing并取决于绑定的新值是大于还是小于当前值。

我创建了下面的草图来演示具有不同转换的相同视图(视图 2)的问题,具体取决于选择了右侧还是左侧的视图。请仅将其视为示例,问题不仅限于三个段,也不仅限于中间视图,也不仅限于消失的过渡等。

在此处输入图像描述

4

1 回答 1

1

更新秘诀是确保过渡以动画触发,并在这样做之前告诉它前进的方向。试试这个:

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())
    }
}
于 2021-02-18T22:34:27.347 回答