I have created a bottom alert that I want to animate when it is to be presented or removed. Currently it is not doing any animation, only showing up and removing itself when needed.
I've tried using .transition(.move(edge: .bottom))
on the actual view but no animation is shown.
How can I add a slide up/down animation for this view?
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))
}
}
}
}
Bottom Alert Builder
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
}
For animation, you need to add your show/hide code inside body of withAnimation
function.
withAnimation {
buildBottomAlert(type: .error)
}
Also, update your buildBottomAlert
function like this.
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()
}
}
}
Note: I have used sleep(nanoseconds:)
instead of asyncAfter(deadline:execute:)
.
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.