简体   繁体   中英

SwiftUI (beta 6) - Animate re-ordering of views

I'm looking for a way to animate the re-ordering of views. Initially I implemented the views in a VStack like so:

@State var someState: State

var body: some View {
    VStack {
        createView(forType: someState.orderedTypes[0])
        createView(forType: someState.orderedTypes[1])
        createView(forType: someState.orderedTypes[2])
    }
}

func createView(forType type: SomeExampleType) -> some View {
    return ...
}

As the @State variable changes, the order in which the views are created may change as well. I initially tried tacking a

.animate(.easeOut)

on the end of the VStack, but it only animates some changes in the subviews, not the order of them. I've also tried using a List instead of a VStack, but no luck there either. Does anybody have any tips on how I can accomplish this without resorting to some hacky ZStack/padding nonsense?

This is largely working for me, provided you put it in a ForEach and you make your views dependent on your state.

@State var items: [Int] = [1, 2, 3, 4, 5]

var body: some View {
    VStack {
        ForEach(items, id: \.self) {
            self.view(with: $0 % 2 == 0 ? .text : .image)
        }
        .animation(.default)

        Button("Randomize") {
            self.items.shuffle()
        }
    }
}

private func view(with type: ViewType) -> some View {
    switch type {
    case .text:
        return AnyView(Text("text"))
    case .image:
        return AnyView(Image(systemName: "house"))
    }
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM