![](/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.