BouncingDots.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import SwiftUI
  15. struct BouncingDots: View {
  16. @State
  17. private var dot1YOffset: CGFloat = 0.0
  18. @State
  19. private var dot2YOffset: CGFloat = 0.0
  20. @State
  21. private var dot3YOffset: CGFloat = 0.0
  22. let animation = Animation.easeInOut(duration: 0.8)
  23. .repeatForever(autoreverses: true)
  24. var body: some View {
  25. HStack(spacing: 8) {
  26. Circle()
  27. .fill(Color.white)
  28. .frame(width: 10, height: 10)
  29. .offset(y: dot1YOffset)
  30. .onAppear {
  31. withAnimation(self.animation.delay(0.0)) {
  32. self.dot1YOffset = -5
  33. }
  34. }
  35. Circle()
  36. .fill(Color.white)
  37. .frame(width: 10, height: 10)
  38. .offset(y: dot2YOffset)
  39. .onAppear {
  40. withAnimation(self.animation.delay(0.2)) {
  41. self.dot2YOffset = -5
  42. }
  43. }
  44. Circle()
  45. .fill(Color.white)
  46. .frame(width: 10, height: 10)
  47. .offset(y: dot3YOffset)
  48. .onAppear {
  49. withAnimation(self.animation.delay(0.4)) {
  50. self.dot3YOffset = -5
  51. }
  52. }
  53. }
  54. .onAppear {
  55. let baseOffset: CGFloat = -2
  56. self.dot1YOffset = baseOffset
  57. self.dot2YOffset = baseOffset
  58. self.dot3YOffset = baseOffset
  59. }
  60. }
  61. }
  62. struct BouncingDots_Previews: PreviewProvider {
  63. static var previews: some View {
  64. BouncingDots()
  65. .frame(width: 200, height: 50)
  66. .background(.blue)
  67. .roundedCorner(10, corners: [.allCorners])
  68. }
  69. }