![](/img/trans.png)
[英]iOS Development: How can I animate the addition/removal of form controls in a view?
[英]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()
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.