Skip to content

Instantly share code, notes, and snippets.

@Aymenworks
Created November 15, 2020 10:51
Show Gist options
  • Save Aymenworks/959da6f37a05c7366a8ec5e2709a5407 to your computer and use it in GitHub Desktop.
Save Aymenworks/959da6f37a05c7366a8ec5e2709a5407 to your computer and use it in GitHub Desktop.
Observation #1: Faces are falling from the sky!
import UIKit
class ViewController: UIViewController {
// MARK: Public
@IBOutlet weak var bottomView: UIView!
// MARK: Private
// 1: the class that will allow us to manage our behaviors aka specific dynamic behavior
private lazy var animator = UIDynamicAnimator(referenceView: self.view)
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let faces: [UIImage] = [
#imageLiteral(resourceName: "aymen5"),#imageLiteral(resourceName: "aymen3"),#imageLiteral(resourceName: "aymen1"),#imageLiteral(resourceName: "aymen2"),#imageLiteral(resourceName: "aymen7"),#imageLiteral(resourceName: "aymen6"),#imageLiteral(resourceName: "aymen4"),#imageLiteral(resourceName: "aymen10"),#imageLiteral(resourceName: "aymen8"),#imageLiteral(resourceName: "aymen9")
]
let gravityBehavior = UIGravityBehavior(items: [])
for (index, face) in faces.enumerated() {
// 2: We delay the creation of the face view to display them "one by one"
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(index*150)) {
// 3: Faces will have a random size
let size: CGFloat = CGFloat([50.0, 65.0, 80.0, 100.0].randomElement()!)
// 4
// x: We positionnate the face randomly in the x-axis, so that faces can fall down from different position
// y: negative so that they are falling from above
let bubbleView = FaceView(
frame: .init(
x: CGFloat.random(in: 0...UIScreen.main.bounds.width-size),
y: -50,
width: size,
height: size
),
image: face
)
self.view.addSubview(bubbleView)
// 5: We add a gravity behavior for each of our face
gravityBehavior.addItem(bubbleView)
}
}
// 6: We ask our "manager" to add the gravity behavior, which will automatically trigger the animation.
animator.addBehavior(gravityBehavior)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment