簡體   English   中英

在 SwiftUI 中動畫添加/刪除視圖

[英]Animate Addition/Removal of View in SwiftUI

我已經創建了一個底部警報,我想在顯示或刪除它時設置動畫。 目前它沒有做任何動畫,只在需要時顯示和刪除自己。

我試過在實際視圖上使用.transition(.move(edge: .bottom))但沒有顯示動畫。

如何為此視圖添加向上/向下滑動動畫?

var body: some View {
    ZStack {
        VStack {
            toolbar
            Spacer()
            switch viewModel.status {
            case .loading:
                LoadingView(isAnimating: $isLoading)
            case .loaded(_):
                productView
            case .error(_):
                Text("Please Retry.")
                    .onAppear {
                        buildBottomAlert(type: .error)
                    }
            }
        }
        
        VStack {
            Spacer()
            if let bottomView = bottomAlertView {
                bottomView
                    .transition(.move(edge: .bottom))
            }
        }
        }
}

底部警報生成器

func buildBottomAlert(type: BottomAlertType) {
    self.bottomAlertView = BottomAlert(type: type)
    self.showBottomAlert = true
    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
        self.removeBottomAlert()
    }
}

func removeBottomAlert() {
    bottomAlertView = nil
    showBottomAlert = false
}

對於動畫,您需要在withAnimation函數體內添加顯示/隱藏代碼。

withAnimation {
    buildBottomAlert(type: .error)
}

另外,像這樣更新您的buildBottomAlert函數。

func buildBottomAlert(type: BottomAlertType) {
    self.bottomAlertView = BottomAlert(type: type)
    self.showBottomAlert = true
    Task {
        //Sleep for 2 seconds
        try await Task.sleep(nanoseconds: 2_000_000_000)
        withAnimation {
            removeBottomAlert()
        }
    }
}

注意:我使用sleep(nanoseconds:)而不是asyncAfter(deadline:execute:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM